简体   繁体   English

用“元素编号”替换数组中的元素(Python)

[英]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).其中第一行读取[0, 2, 3]因为第二个元素被检查,通过了测试,然后被替换(等等)。 Can anyone think of any solutions?谁能想到任何解决方案? I imagine that numpy's indexing will be quite useful here.我想numpy的索引在这里会非常有用。 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) (来自 IPython 交互式控制台会话)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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