如果该列中的所有元素均满足条件,则删除该多维数组中的一列

编程入门 行业动态 更新时间:2024-10-28 14:32:06
本文介绍了如果该列中的所有元素均满足条件,则删除该多维数组中的一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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]

更多推荐

如果该列中的所有元素均满足条件,则删除该多维数组中的一列

本文发布于:2023-10-27 16:22:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533914.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   组中   元素   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!