如何删除numpy数组中的列? [英] How to remove a column in a numpy array?
问题描述
想象一下,我们有一个5x4的矩阵. 我们只需要删除第一个维度. 如何使用 numpy 做到这一点?
Imagine we have a 5x4 matrix. We need to remove only the first dimension. How can we do it with numpy?
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 16., 17., 18., 19.]], dtype=float32)
我尝试过:
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?
推荐答案
如果要从2D Numpy数组中删除列,则可以指定这样的列
If you want to remove a column from a 2D Numpy array you can specify the columns like this
保留所有行并删除第0列(或从第1列开始直到结尾)
to keep all rows and to get rid of column 0 (or start at column 1 through the end)
a[:,1:]
另一种方式,您可以指定要保留的列(并根据需要更改顺序) 这将保留所有行,并且仅使用列0、2、3
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
a[:,[0,2,3]]
有关此文档,可在此处
如果您想要专门删除列的内容,可以执行以下操作:
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]
和@hpaulj调出numpy.delete()
and @hpaulj brought up numpy.delete()
这将是如何返回沿轴= 1移除2列(0和2)的"a"视图的方法.
This would be how to return a view of 'a' with 2 columns removed (0 and 2) along axis=1.
np.delete(a,[0,2],1)
这实际上并没有从'a'中删除项目,它的返回值是一个新的numpy数组.
This doesn't actually remove the items from 'a', it's return value is a new numpy array.
这篇关于如何删除numpy数组中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!