简体   繁体   中英

numpy logical operation on 2D array

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

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

Why your approach can't work:

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]]
#                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM