开发者

Replacing column values in an array using putmask and preserving order

开发者 https://www.devze.com 2023-03-09 00:59 出处:网络
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 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) sets x.flat[n] = y[n] for each n where mask.flat[n] is True.

In [17]: list(x.flat)
Out[17]: [21.0, 2.0, 22.0, 4.0, 23.0, 6.0, 24.0, 8.0, 25.0, 10.0]

In [18]: list(mask.flat)
Out[18]: [True, False, True, False, True, False, True, False, True, False]

Since mask.flat alternates between True and False, you end up setting every other value in x.flat with every other value in y.

Since y is not the same size as x, the values in y are repeated. This is what leads to the (undesired) alternating values you see in x after calling putmask(x,mask,y).

If instead you wish to assign new values to x wherever mask is True, then all you need is assignment with numpy indexing:

x[mask]=y

For example,

import numpy as np
x = np.array([[  1.,   2.],
        [  3.,   4.],
        [  5.,   6.],
        [  7.,   8.],
        [  9.,  10.]])
mask = np.array([[ True, False],
           [ True, False],
           [ True, False],
           [ True, False],
           [ True, False]])
y = np.array([ 21.,  22.,  23.,  24.,  25.])
x[mask]=y
print(x)
# [[ 21.   2.]
#  [ 22.   4.]
#  [ 23.   6.]
#  [ 24.   8.]
#  [ 25.  10.]]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号