Reputation:
Suppose we have a set of values: n
-rows and 6
columns (n,6).
How to replace 4th element in a row to be equal to the 3rd element if the 3rd element is more than the 4th?
I tried to do it in such a way:.
griddata[:,3][griddata[:,2] > griddata[:,3]] = griddata[:,2]
TypeError: 'numpy.float64' object does not support item assignment
Upvotes: 2
Views: 1742
Reputation: 152657
You could use np.where
instead:
griddata[:,3] = np.where(griddata[:,2] > griddata[:,3], griddata[:,2], griddata[:,3])
That replaces griddata[:,3]
with griddata[:,2]
everywhere that the condition (griddata[:,2] > griddata[:,3]
) is True otherwise with the third argument (the original): griddata[:,3]
.
A small sample:
>>> griddata = np.array([[1,2,3,4,5,6], [6,5,4,3,2,1]])
>>> griddata
array([[1, 2, 3, 4, 5, 6],
[6, 5, 4, 3, 2, 1]])
>>> griddata[:,3] = np.where([griddata[:,2] > griddata[:,3]], griddata[:,2],
>>> griddata
array([[1, 2, 3, 4, 5, 6],
[6, 5, 4, 4, 2, 1]])
griddata[:,3][griddata[:,2] > griddata[:,3]]
contains x
elements where x
is the number of True
for your condition, however griddata[:,2]
contains always n
elements. So in any case (except when griddata[:,2] > griddata[:,3]
is True for all rows) you will try to put n
items in x
slots. That just can't work.
You would need to mask both sides to make it work:
griddata[:,3][griddata[:,2] > griddata[:,3]] = griddata[:,2][griddata[:,2] > griddata[:,3]]
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 2