Python 如何删除numpy数组中的列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34007632/
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 remove a column in a numpy array?
提问by minerals
Imagine we have a 5x4 matrix. We need to remove only the first dimension. How can we do it with numpy?
想象一下,我们有一个 5x4 的矩阵。我们只需要删除第一个维度。我们如何用numpy做到这一点?
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 16., 17., 18., 19.]], dtype=float32)
I tried:
我试过:
arr = np.arange(20, dtype=np.float32)
matrix = arr.reshape(5, 4)
new_arr = numpy.delete(matrix, matrix[:,0])
trimmed_matrix = new_arr.reshape(5, 3)
It looks a bit clunky. Am I doing it correctly? If yes, is there a cleaner way to remove the dimension without reshaping?
它看起来有点笨重。我做得对吗?如果是,是否有更清洁的方法来去除尺寸而不重塑?
采纳答案by Back2Basics
If you want to remove a column from a 2D Numpy array you can specify the columns like this
如果要从 2D Numpy 数组中删除一列,可以像这样指定列
to keep all rows and to get rid of column 0 (or start at column 1 through the end)
保留所有行并删除第 0 列(或从第 1 列开始直到结束)
a[:,1:]
another way you can specify the columns you want to keep ( and change the order if you wish) This keeps all rows and only uses columns 0,2,3
您可以指定要保留的列的另一种方法(并根据需要更改顺序)这会保留所有行并且仅使用列 0,2,3
a[:,[0,2,3]]
The documentation on this can be found here
可以在此处找到有关此的文档
And if you want something which specifically removes columns you can do something like this:
如果您想要专门删除列的内容,您可以执行以下操作:
idxs = list.range(4)
idxs.pop(2) #this removes elements from the list
a[:, idxs]
and @hpaulj brought up numpy.delete()
@hpaulj 提出了 numpy.delete()
This would be how to return a view of 'a' with 2 columns removed (0 and 2) along axis=1.
这将是如何返回沿轴 = 1 删除 2 列(0 和 2)的“a”视图。
np.delete(a,[0,2],1)
This doesn't actually remove the items from 'a', it's return value is a new numpy array.
这实际上并没有从 'a' 中删除项目,它的返回值是一个新的 numpy 数组。
回答by yevgeniy
You don't need the second reshape.
你不需要第二次重塑。
matrix=np.delete(matrix,0,1)
回答by hpaulj
The correct way to use delete
is to specify index and dimension, eg. remove the 1st (0) column (dimension 1):
正确的使用方法delete
是指定索引和维度,例如。删除第一 (0) 列(维度 1):
In [215]: np.delete(np.arange(20).reshape(5,4),0,1)
Out[215]:
array([[ 1, 2, 3],
[ 5, 6, 7],
[ 9, 10, 11],
[13, 14, 15],
[17, 18, 19]])
other expressions that work:
其他有效的表达方式:
np.arange(20).reshape(5,4)[:,1:]
np.arange(20).reshape(5,4)[:,[1,2,3]]
np.arange(20).reshape(5,4)[:,np.array([False,True,True,True])]