如果该列中的所有元素均满足条件,则删除该多维数组中的一列 [英] Delete a column in a multi-dimensional array if all elements in that column satisfy a condition

查看:72
本文介绍了如果该列中的所有元素均满足条件,则删除该多维数组中的一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,例如;

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]

这篇关于如果该列中的所有元素均满足条件,则删除该多维数组中的一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆