如何从python中的数组(或矩阵)中提取除一列以外的所有列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24027040/
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
How to extract all columns but one from an array (or matrix) in python?
提问by Ferdinando Randisi
Given a numpy 2d array (or a matrix), I would like to extract all the columns but the i-th.
给定一个 numpy 二维数组(或矩阵),我想提取除第 i 列之外的所有列。
E. g. from
例如 从
1 2 3 4
2 4 6 8
3 6 9 12
I would like to have, e.g.
我想要,例如
1 2 3
2 4 6
3 6 9
or
或者
1 2 4
2 4 8
3 6 12
I cannot find a pythonic way to do this. I now that you can extract given columns by simply
我找不到一种pythonic的方法来做到这一点。我现在可以简单地提取给定的列
a[:,n]
or
或者
a[:,[n,n+1,n+5]]
But what about extracting all of them but one?
但是除了一个之外,提取所有这些呢?
采纳答案by Jaime
Since for the general case you are going to be returning a copy anyway, you may find yourself producing more readable code by using np.delete
:
由于在一般情况下,您无论如何都会返回副本,因此您可能会发现自己使用np.delete
以下方法生成了更具可读性的代码:
>>> a = np.arange(12).reshape(3, 4)
>>> np.delete(a, 2, axis=1)
array([[ 0, 1, 3],
[ 4, 5, 7],
[ 8, 9, 11]])
回答by Peter Gibson
Take a look at numpy's advanced slicing
看看numpy的高级切片
>>> import numpy as np
>>> a = np.array([[1,2,3,4], [2,4,6,8], [3,6,9,12]])
>>> a[:,np.array([True, True, False, True])]
array([[ 1, 2, 4],
[ 2, 4, 8],
[ 3, 6, 12]])
回答by chrisb
Use a slice that excludes the last element.
使用排除最后一个元素的切片。
In [19]: a[:,:-1]
Out[19]:
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
If you want something other than the last element I'd just build a list to select with.
如果你想要的不是最后一个元素,我只需要建立一个列表来选择。
In [20]: selector = [x for x in range(a.shape[1]) if x != 2]
In [21]: a[:, selector]
Out[21]:
array([[ 1, 2, 4],
[ 2, 4, 8],
[ 3, 6, 12]])
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
回答by Nathan
The answers given already can easily be adapted to selecting all but a list of columns, but here are a couple of explicit examples:
已经给出的答案可以很容易地适用于选择除列列表之外的所有列,但这里有几个明确的例子:
In [1]: import numpy as np
In [2]: a = np.arange(12).reshape(3, 4)
In [3]: a
Out[3]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [4]: drop_cols = [0, 3]
# option 1: delete the columns you don't want (like @Jaime)
# (this is really the most straightforward)
In [5]: np.delete(a, drop_cols, axis=1)
Out[5]:
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])
# option 2: pass the indices of columns to keep (like @chrisb)
In [6]: a[:, [i for i in range(a.shape[1]) if i not in drop_cols]]
Out[6]:
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])
# option 3: use an array of T/F for each col (like @Peter Gibson)
In [7]: a[:, [i not in drop_cols for i in range(a.shape[1])]]
Out[7]:
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])