Python 根据单个单元格上的条件从numpy数组中删除列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21016684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:48:17  来源:igfitidea点击:

Delete columns from numpy array depending on a condition on a single cell

pythonarraysnumpy

提问by user3176697

Above all, sorry for my bad English.

最重要的是,对不起我的英语不好。

I have this array t:

我有这个数组t

array([[ 0,  1,  2,  0,  4,  5,  6,  7,  8,  9],
       [ 0, 11,  0, 13,  0, 15,  0, 17, 18,  0]])

I would like to delete the columns where the value of second line is null. Here, I would like to delete the columns 0, 2, 4, 6 and 9, to obtain this array:

我想删除第二行值为空的列。在这里,我想删除第 0、2、4、6 和 9 列,以获取此数组:

array([[  1,   0,   5,   7,  8 ],
       [ 11,  13,  15,  17, 18 ]])

I tried with np.sum()but didn't succeed.

我尝试过np.sum()但没有成功。

采纳答案by Eelco Hoogendoorn

Similar to Juh_, but more expressive, and avoiding some minor unnecessary performance overhead. A grand total of 12 highly pythonic, explicit and unambigious characters. This is really numpy 101; if you are still trying to wrap your head around this, you would do yourself a favor by reading a numpy primer.

类似于 Juh_,但更具表现力,并避免了一些不必要的小性能开销。总共 12 个高度 pythonic、明确和明确的字符。这真的是 numpy 101;如果您仍在试图解决这个问题,那么您可以通过阅读一本 numpy 入门书来帮自己一个忙。

import numpy as np
a = np.array([[ 0,  1,  2,  0,  4,  5,  6,  7,  8,  9],
              [ 0, 11,  0, 13,  0, 15,  0, 17, 18,  0]])
print a[:,a[1]!=0]

回答by Krzysztof Rosiński

I got this working like this:

我得到了这样的工作:

data = array([[ 0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [ 0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])
res = array([(a, b,) for a, b in zip(data[0], data[1]) if b]).transpose()

got the result

得到了结果

In [23]: res
Out[23]: 
array([[ 1,  0,  5,  7,  8],
       [11, 13, 15, 17, 18]])

回答by eskaev

With numpy.delete:

numpy.delete

a = np.array([[0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])

indices = [i for (i,v) in enumerate(a[1]) if v==0]
# [0, 2, 4, 6, 9]

a = np.delete(a, indices, 1)
# array([[ 1,  0,  5,  7,  8], [11, 13, 15, 17, 18]])

回答by Juh_

Simple (fully numpy) solution:

简单(完全麻木)的解决方案:

import numpy as np

t = np.array([[ 0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [ 0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])
indices_to_keep = t[1].nonzero()[0]

print t[:,indices_to_keep]
# [[ 1  0  5  7  8]
#  [11 13 15 17 18]]

回答by alko

Using np.where:

使用np.where

>>> t.T[np.where(t[1])].T
array([[ 1,  0,  5,  7,  8],
       [11, 13, 15, 17, 18]])