首页 > 解决方案 > 删除数组的特定值:Python

问题描述

我有一个形状数组(1179648, 909)。问题是某些行仅填充了0'。我正在检查如下:

for i in range(spectra1Only.shape[0]):
    for j in range(spectra1Only.shape[1]):
        if spectra1Only[i,j] == 0:

我现在想删除整行,[i]如果有任何0似乎只获得少量所需的数据。

我的问题是:最好的方法是什么?Remove? Del? numpy.delete? 还是有什么其他方法?

标签: pythonarraysnumpyindexing

解决方案


您可以将布尔索引与np.anyalong 一起使用axis=1

spectra1Only = spectra1Only[~(spectra1Only == 0).any(1)]

这是一个演示:

A = np.random.randint(0, 9, (5, 5))

print(A)

[[5 0 3 3 7]
 [3 5 2 4 7]
 [6 8 8 1 6]
 [7 7 8 1 5]
 [8 4 3 0 3]]

print(A[~(A == 0).any(1)])

[[3 5 2 4 7]
 [6 8 8 1 6]
 [7 7 8 1 5]]

推荐阅读