简体   繁体   English

从numpy数组中删除行和列

[英]remove rows and columns from numpy array

I have an array like this: 我有一个像这样的数组:

a = np.array([[1,2,3,4,5],
[6,0,8,9,10],
[11,12,13,14,15],
[16,0,0,19,20]])

And I would like to remove columns and rows where there is a 0 value, so the new a should be like: 而且我想删除具有0值的列和行,因此新的a应该像这样:

array([[1,4,5],
[11,14,15]])

How to work this out using indexing? 如何使用索引解决这个问题?

>>> a[(a != 0).all(axis=1)][:,(a != 0).all(axis=0)]
array([[ 1,  4,  5],
       [11, 14, 15]])

Finding the elements of a that are non-zero is really easy: 找到的元素a是非零是很容易的:

>>> (a != 0)
array([[ True,  True,  True,  True,  True],
       [ True, False,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True, False, False,  True,  True]], dtype=bool)

And then you can just use all , specifying the axis, to find the rows you want to keep: 然后,您可以使用all (指定轴)来查找要保留的行:

>>> (a != 0).all(axis=1)
array([ True, False,  True, False], dtype=bool)

and the same thing for the columns: 对于列也是如此:

>>> (a != 0).all(axis=0)
array([ True, False, False,  True,  True], dtype=bool)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM