gpt4 book ai didi

python - 在 Python 中打印二维矩阵中的所有非零元素

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:31 25 4
gpt4 key购买 nike

我有一个稀疏的二维矩阵,通常是这样的:

test
array([[ 1., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 2., 1., 0.],
[ 0., 0., 0., 1.]])

我对“测试”中的所有非零元素感兴趣

index = numpy.nonzero(test) 返回一个数组元组,为我提供非零元素的索引:

index 
(array([0, 2, 2, 3]), array([0, 1, 2, 3]))

对于每一行,我想打印出所有非零元素,但跳过所有仅包含零元素的行。

我将不胜感激。

感谢您的提示。这解决了问题:

>>> test
array([[ 1., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 2., 1., 0.],
[ 0., 0., 0., 1.]])

>>> transp=np.transpose(np.nonzero(test))
>>> transp
array([[0, 0],
[2, 1],
[2, 2],
[3, 3]])

>>> for index in range(len(transp)):
row,col = transp[index]
print 'Row index ',row,'Col index ',col,' value : ', test[row,col]

给我:

  Row index  0 Col index  0  value :  1.0
Row index 2 Col index 1 value : 2.0
Row index 2 Col index 2 value : 1.0
Row index 3 Col index 3 value : 1.0

最佳答案

给定

rows, cols = np.nonzero(test)

你也可以使用所谓的advanced integer indexing :

test[rows, cols]

例如,

test = np.array([[ 1.,  0.,  0.,  0.],
[ 0., 0., 0., 0.],
[ 0., 2., 1., 0.],
[ 0., 0., 0., 1.]])

rows, cols = np.nonzero(test)

print(test[rows, cols])

产量

array([ 1.,  2.,  1.,  1.])

关于python - 在 Python 中打印二维矩阵中的所有非零元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31288765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com