[英]Constructing piecewise function from changepoints in Numpy
I want to construct a piecewise function from changepoints in python. 我想从python中的变换点构造一个分段函数。 I expect my inputs and outputs to be large, so speed is important. 我希望我的输入和输出很大,所以速度很重要。
Input: 输入:
A = [1,7, 1000, 1500]
int numpy数组: A = [1,7, 1000, 1500]
B = [True, False, True, True, False, True, False, False]
where the length of A
is equal to the number of True
in B
bool numpy array: B = [True, False, True, True, False, True, False, False]
其中A
的长度等于B
的True
数 Output: 输出:
C = [1, 1, 7, 1000, 1000, 1500, 1500, 1500]
where the length of C
is the same as the length of B
int numpy array: C = [1, 1, 7, 1000, 1000, 1500, 1500, 1500]
1,1,7,1000,1000,1500,1500,1500 C = [1, 1, 7, 1000, 1000, 1500, 1500, 1500]
其中C
的长度与B
的长度相同 Essentially each element of A
is repeated until the next True
in B
shows up in which case the next element of A
is used. 基本上, A
每个元素都会重复,直到B
中的下一个True
出现,在这种情况下,使用A
的下一个元素。
In [1]: import numpy
In [2]: A = numpy.array([1, 7, 1000, 1500])
In [3]: B = numpy.array([True, False, True, True, False, True, False, False])
In [4]: A[B.cumsum() - 1]
Out[4]: array([ 1, 1, 7, 1000, 1000, 1500, 1500, 1500])
B.cumsum() - 1
computes which element of A to use for each element of the output, and then A[B.cumsum() - 1]
extracts those elements. B.cumsum() - 1
计算A的哪个元素用于输出的每个元素,然后A[B.cumsum() - 1]
提取这些元素。 You could probably also work out a way to use numpy.repeat
to do this. 您可能还可以尝试使用numpy.repeat
来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.