using multiple functions with correlated arrays Numpy Python

陌路散爱 提交于 2021-02-15 07:38:18

问题


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.

Function:

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)

Error Output:

---------------------------------------------------------------------------
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,)

回答1:


your slice notation isn't doing what you think it is:

in: Numbers[:-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])

That is every element in Numbers except for the last, 360286.

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])

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.



来源:https://stackoverflow.com/questions/65999759/using-multiple-functions-with-correlated-arrays-numpy-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!