我有一个多维数组,例如;
I have a multi-dimensional array such as;
a = [[1,1,5,12,0,4,0], [0,1,2,11,0,4,2], [0,4,3,17,0,4,9], [1,3,5,74,0,8,16]]如何删除如果该列中的所有条目都等于零?在数组a中,这意味着删除第4列,结果是:
How can I delete the column if all entries within that column are equal to zero? In the array a that would mean deleting the 4th column resulting in:
a = [[1,1,5,12,4,0], [0,1,2,11,4,2], [0,4,3,17,4,9], [1,3,5,74,8,16]]Nb我已将a编写为嵌套列表,但仅讲清楚我也不知道数组中零列的先验位置。
N.b I've written a as a nested list but only to make it clear. I also don't know a priori where the zero column will be in the array.
到目前为止,我的尝试只是找到所有元素均相等的列的索引归零:
My attempt so far only finds the index of the column in which all elements are equal to zero:
a = np.array([[1,1,5,12,0,4,0],[0,1,2,11,0,4,2],[0,4,3,17,0,4,9],[1,3,5,74,0,8,16]]) b = np.vstack(a) ind = [] for n,m in zip(b.T,range(len(b.T))): if sum(n) == 0: ind.append(m)有什么方法可以实现?
Is there any way to achieve this?
推荐答案使用已经拥有的代码,您可以执行以下操作:
With the code you already have, you can just do:
for place in ind: for sublist in a: del sublist[place]哪个工作完成了,但不是很令人满意...
Which gets the job done but is not very satisfactory...
编辑:numpy强大
import numpy as np a = np.array(a) a = a[:, np.sum(a, axis=0)!=0]更多推荐
如果该列中的所有元素均满足条件,则删除该多维数组中的一列
发布评论