【问题标题】:Delete a column in a multi-dimensional array if all elements in that column satisfy a condition如果该列中的所有元素都满足条件,则删除多维数组中的列
【发布时间】:2014-02-25 23:33:41
【问题描述】:

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

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 列导致:

 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]]

N.b 我将 a 写成嵌套列表,但只是为了说明问题。我也不知道数组中零列的位置。

到目前为止,我的尝试只找到了所有元素都为零的列的索引:

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)

有什么方法可以实现吗?

【问题讨论】:

    标签: python arrays multidimensional-array


    【解决方案1】:

    使用您已有的代码,您可以这样做:

    for place in ind:
        for sublist in a:
            del sublist[place]
    

    完成了工作但不是很令人满意......


    编辑:numpy 很强大

    import numpy as np
    a = np.array(a)
    a = a[:, np.sum(a, axis=0)!=0]
    

    【讨论】:

    • 我同意,看起来有点麻烦 - 你知道更 Python 的方式吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2020-11-11
    • 2013-09-08
    相关资源
    最近更新 更多