numpy 在Python中打印数组中不等于零的所有行

6l7fqoea  于 2023-01-02  发布在  Python
关注(0)|答案(4)|浏览(236)

我有一个数组out。我想打印至少有一个非零元素的行号。但是,我得到了一个错误。我给出了预期的输出。

import numpy as np

out = np.array([[  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [  0.        , 423.81345923,   0.        , 407.01354328,
        419.14952534,   0.        , 212.13245959,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [402.93473651,   0.        , 216.08166277, 407.01354328,
          0.        , 414.17017965,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ]])

for i in range(0,len(out)):
    if (out[i]==0):
        print(i)
    else:
        print("None")

错误是

in <module>
    if (out[i]==0):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

预期的输出为

[1,2]
o7jaxewo

o7jaxewo1#

import numpy as np

out = ... # 2d array here

rows = np.where(out.any(axis=1))[0].tolist()

# rows:
# [1, 2]
rjee0c15

rjee0c152#

您的代码问题在于out[i]是一个数组。当您检查此数组是否等于零时,它返回一个布尔值数组。if语句随后返回一个错误。下面的代码应该可以工作:

solution = []
for idx, e in enumerate(out):
    if any(e): # if any element of the array is nonzero
        solution.append(idx)
print(solution)

输出为:

[1, 2]

希望这能有所帮助!

xkftehaa

xkftehaa3#

import numpy as np

out = np.array([[  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [  0.        , 423.81345923,   0.        , 407.01354328,
        419.14952534,   0.        , 212.13245959,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [402.93473651,   0.        , 216.08166277, 407.01354328,
          0.        , 414.17017965,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ]])

for i in range(0,len(out)):
    if (out[i].sum()!=0):
        print(i)
    else:
        print("None")

这将合计每个索引的所有值,并打印包含任何非零值的所有行。

ht4b089n

ht4b089n4#

我们在numpy中有whereunique属性,可以帮助您实现这一点。

get_index = np.where(out != 0)[0]
rows = np.unique(get_index)
print(rows)

相关问题