I have a function that works perfectly. It takes a numpy 2D array and do something by the array then returns it back. I try to use the returned value to fill an array by a condition. look at below code:
>>> import numpy as np
>>> x=np.random.randint(20, size=(4,5))
>>> y=np.zeros_like(x) * np.nan
>>> x
array([[19, 0, 6, 17, 5],
[18, 18, 10, 19, 9],
[ 2, 5, 10, 5, 15],
[ 9, 3, 0, 6, 9]])
>>> y
array([[ nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan]])
>>> y[ x>15 ] = 1000
>>> y
array([[ 1000., nan, nan, 1000., nan],
[ 1000., 1000., nan, 1000., nan],
[ nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan]])
problem is when add a function like.
>>> def foo(x):
return x*2
>>> y[ x>15 ] = foo(x)
Warning (from warnings module):
File "__main__", line 1
FutureWarning: assignment exception type will change in the future
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
y[ x>15 ] = foo(x)
ValueError: boolean index array should have 1 dimension
or something like:
>>> _=foo(x)
>>> y[ x>15 ]=_
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
y[ x>15 ]=_
ValueError: boolean index array should have 1 dimension
why it does not work any more!?
np.where(x>15, foo(x), y).y[x>15] = foo(x[x>15])