将多个函数与相关数组结合使用Numpy Python [英] using multiple functions with correlated arrays Numpy Python
问题描述
假定下面的函数根据 Set
和 Numbers
计算 Uval
和 Lval
函数.对于前两个数字,与 U
和 52599
相关,而与 L
和 52550
相关,因为第二个数字数字具有标签 L
的标签,将使用 Lval
公式.前一个函数是 previous = numbers [1:]
,而当前函数是 current = numbers [:-1]
.因此(52550-52599)/52550 * -100
将是前两个数字的计算.这些方程应该一直计算到 Set
和 Numbers
数组的末尾.但是代码下面给了我错误, Set
和 Numbers
数组的长度均为15.
The function below is supposed compute either the Uval
and Lval
functions in accordance to Set
and Numbers
. For the first two numbers U
and 52599
are in relation and L
and 52550
are in relation, since the second number has the label L
the Lval
equation is used. The previous number is function is previous = numbers[1:]
and the current function is current = numbers[:-1]
. So (52550 - 52599)/52550 * -100
will be the computation for the first two numbers. The equations are supposed to be computed until the end of the Set
and Numbers
arrays. However the code gives me the error down below, both the Set
and Numbers
array have the length of 15.
功能:
Set = np.array(['U', 'L', 'U', 'L', 'U', 'L', 'U', 'L', 'U', 'L', 'U', 'L', 'U', 'L', 'U'])
Numbers = np.array([ 52599, 52550, 53598, 336368, 336875, 337466, 338292, 356587, 357474, 357763, 358491, 358659, 359041, 360179, 360286])
Lval = (Numbers[:-1] - Numbers[1:])/Numbers[:-1] * -100
Uval = (Numbers[1:] - Numbers[:-1])/ Numbers[1:] * -100
Numbers * np.where(Set == 'U', Uval, Lval)
错误输出:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-3ddad609950b> in <module>
4 Uval = (Numbers[1:] - Numbers[:-1])/ Numbers[1:] * -100
5 print(len(Set))
----> 6 Numbers * np.where(Set == 'U', Uval, Lval)
<__array_function__ internals> in where(*args, **kwargs)
ValueError: operands could not be broadcast together with shapes (15,) (14,) (14,)
推荐答案
您的切片符号没有按照您的想象做:
your slice notation isn't doing what you think it is:
in: Numbers[:-1]
对数组中的元素进行 not 移位1.它将所有元素向上移动,但不包括最后一个元素.输出为:
does not shift elements in the array by 1. It takes all elements up to but not including the last element. The output is:
in: Numbers[:-1]
out: array([ 52599, 52550, 53598, 336368, 336875, 337466, 338292, 356587,
357474, 357763, 358491, 358659, 359041, 360179])
那是Numbers中除最后一个360286之外的所有元素.
That is every element in Numbers except for the last, 360286.
您需要使用np.roll()函数将元素移动一个.但这会将最后一个元素滚动到前面:
You need to use the np.roll() function to shift elements by one. This will roll the last element to the front though:
in: np.roll(Numbers, 1)
out: array([360286, 52599, 52550, 53598, 336368, 336875, 337466, 338292,
356587, 357474, 357763, 358491, 358659, 359041, 360179])
所以您必须处理最开始和最后一个数字的极端情况,例如您的数组长度为15,因此对于L或U您只能获得14个新元素.
so you have to handle the edge case of what to do with the very first and very last numbers, e.g. your arrays are length 15, so you can only get 14 new elements for either L or U.
这篇关于将多个函数与相关数组结合使用Numpy Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!