获取2D数组的非零元素的索引 [英] get indicies of non-zero elements of 2D array

查看:89
本文介绍了获取2D数组的非零元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>获取零和非零元素的索引在数组中,我可以像这样在numpy中获得一维数组中非零元素的索引:

From Getting indices of both zero and nonzero elements in array, I can get indicies of non-zero elements in a 1 D array in numpy like this:

indices_nonzero = numpy.arange(len(array))[~bindices_zero]

有没有办法将其扩展到2D数组?

Is there a way to extend it to a 2D array?

推荐答案

您可以使用numpy.nonzero

以下代码不言自明

You can use numpy.nonzero

The following code is self-explanatory

import numpy as np

A = np.array([[1, 0, 1],
              [0, 5, 1],
              [3, 0, 0]])
nonzero = np.nonzero(A)
# Returns a tuple of (nonzero_row_index, nonzero_col_index)
# That is (array([0, 0, 1, 1, 2]), array([0, 2, 1, 2, 0]))

nonzero_row = nonzero[0]
nonzero_col = nonzero[1]

for row, col in zip(nonzero_row, nonzero_col):
    print("A[{}, {}] = {}".format(row, col, A[row, col]))
"""
A[0, 0] = 1
A[0, 2] = 1
A[1, 1] = 5
A[1, 2] = 1
A[2, 0] = 3
"""

您甚至可以做到这一点

A[nonzero] = -100
print(A)
"""
[[-100    0 -100]
 [   0 -100 -100]
 [-100    0    0]]
 """

其他变化

np.where(array)

等效于np.nonzero(array) 但是,np.nonzero是首选,因为它的名称很清楚

Other variations

np.where(array)

It is equivalent to np.nonzero(array) But, np.nonzero is preferred because its name is clear

等效于np.transpose(np.nonzero(array))

print(np.argwhere(A))
"""
[[0 0]
 [0 2]
 [1 1]
 [1 2]
 [2 0]]
 """

这篇关于获取2D数组的非零元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆