迭代时如何使用.delete()删除numpy中的特定数组? [英] How to use .delete() to delete specific array in numpy when iterate it?
问题描述
首先,我已阅读有关此问题
我有一个np.array(来自图片)
I have a np.array(from a picture)
[[255 255 255 ... 255 255 255]
[255 255 0 ... 255 255 255]
[255 255 255 ... 255 255 255]
...
[255 255 0 ... 0 255 255]
[255 255 0 ... 255 255 255]
[255 255 255 ... 255 255 255]]
我要删除0
量小于特定值的行.
我的代码是:
I want to delete the row which the amount of 0
is smaller than a specific value.
My code is:
import numpy
from collections import Counter
for i in range(pixelarray.shape[0]):
# Counter(pixelarray[i])[0] represent the amount of 0 in one row.
if Counter(pixelarray[i])[0] < 2: # check the amount of 0,if it is smaller than 2,delete it.
pixelarray = np.delete(pixelarray,i,axis=0) # delete the row
print(pixelarray)
但是它引发了错误:
Traceback (most recent call last):
File "E:/work/Compile/python/OCR/PictureHandling.py", line 23, in <module>
if Counter(pixelarray[i])[0] <= 1:
IndexError: index 183 is out of bounds for axis 0 with size 183
我该怎么办?
推荐答案
np.delete
is probably not the best choice for this problem. This can be solved simply by masking out the rows that do not meet the required criteria. For that, you start by counting the number of zeros per row:
zeros_per_row = (pixelarray == 0).sum(1)
这首先将pixelarray
中的每个值都与零进行比较,然后将其列(轴1
)求和(计算True
值的数量),因此您将获得每行中零的数量.然后,您可以简单地执行以下操作:
This first compares each value in pixelarray
with zero, and then sums (counts the number of True
values) its columns (axis 1
), so you get the number of zeros in each row. Then, you can simply do:
rows_with_min_zeros = pixelarray[zeros_per_row >= MIN_ZEROS]
在这里,zeros_per_row >= MIN_ZEROS
生成一个布尔数组,其中每个大于或等于MIN_ZEROS
的值都是True
.使用布尔数组索引,可以用于排除False
所在的行,即零位数小于MIN_ZEROS
的行.
Here, zeros_per_row >= MIN_ZEROS
produces a boolean array where every value larger or equal to MIN_ZEROS
is True
. Using boolean array indexing, this can be used to exclude the rows where it is False
, that is, the rows where the number of zeros is less than MIN_ZEROS
.
这篇关于迭代时如何使用.delete()删除numpy中的特定数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!