简体   繁体   中英

Replacing Elements in an Array with its “Element Number” (Python)

I have an array that looks something like this:

np.array([[0 , 5, 1], [0, 0, 3], [1, 7, 0]])

I want to check that each element is nonzero, and if it is nonzero replace it with a number that tracks how many elements it has checked. That is, I want the final product to look like

np.array([[0, 2, 3], [0, 0, 6], [7, 8, 0]])

where the first row reads [0, 2, 3] because the second element was checked second, passed the test, and then replaced (and so on). Can anyone think of any solutions? I imagine that numpy's indexing will be quite useful here. Thanks!

You can do:

np.where(a == 0, a, np.arange(a.size).reshape(a.shape) + 1)

In case if you need to modify the initial array - additional approach using mask array:

(from IPython interactive console session)

In [211]: arr = np.array([[0, 5, 1], [0, 0, 3], [1, 7, 0]])

In [212]: m = arr.nonzero()

In [213]: arr[m] = np.arange(1, arr.size+1).reshape(arr.shape)[m]

In [214]: arr
Out[214]: 
array([[0, 2, 3],
       [0, 0, 6],
       [7, 8, 0]])

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