I have a numpy array of floats and I wish to recalculate new values using a formula that depends on the column being recalculated.
I have initially tried to loop over the columns, masking the array except the column to be recalculated, and the replacing the values with the new ones with numpy.putmask but this does not retain the order, as it attempts to place a value in each element and failing that tries with the next calculated value on the next element, à la:
>>> import numpy as np
>>> x = [[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 10.]]
>>> mask = [[ True, False],
[ True, False],
[ True, False],
[ True, False],
[ True, False]]
>>> y = [ 21., 22., 23., 24., 25.]
>>> np.putmask(x,mask,y)
>>> print x
[[ 21. 2.]
[ 23. 4.]
[ 25. 6.]
[ 22. 8.]
[ 24. 10.]]
I need a solution that will retry with the same value until it finds a True value, such that x would look like:
[[ 21. 2.]
[ 22. 4.]
[ 23. 6.]
[ 24. 8.]
[ 25. 10.]]
Any solutions or other methods welcomed. Thanks.
putmask(x,mask,y)setsx.flat[n] = y[n]for eachnwheremask.flat[n]is True.Since
mask.flatalternates betweenTrueandFalse, you end up setting every other value inx.flatwith every other value iny.Since
yis not the same size asx, the values inyare repeated. This is what leads to the (undesired) alternating values you see inxafter callingputmask(x,mask,y).If instead you wish to assign new values to
xwherevermaskis True,then all you need is assignment with numpy indexing:
For example,