提取numpy矩阵的前n列

时间:2012-05-16 19:09:29

标签: python numpy

我有一个这样的数组:

  array([[-0.57098887, -0.4274751 , -0.38459931, -0.58593526],
         [-0.22279713, -0.51723555,  0.82462029,  0.05319973],
         [ 0.67492385, -0.69294472, -0.2531966 ,  0.01403201],
         [ 0.41086611,  0.26374238,  0.32859738, -0.80848795]])

现在我想提取以下内容:

   [-0.57098887, -0.4274751]
   [-0.22279713, -0.51723555]
   [ 0.67492385, -0.69294472]
   [ 0.41086611,  0.26374238]

所以基本上只是前两列..

2 个答案:

答案 0 :(得分:57)

如果您的数组是a

In [11]: a[:,:2]
Out[11]: 
array([[-0.57098887, -0.4274751 ],
       [-0.22279713, -0.51723555],
       [ 0.67492385, -0.69294472],
       [ 0.41086611,  0.26374238]])

答案 1 :(得分:7)

我知道这是一个很老的问题 -

A = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

让我们说,你想要提取前2行和前3列

A_NEW = A[0:2,0:3]
A_NEW = [[1,2,3],[4,5,6]]

理解语法

A_NEW = A[start_index : stop_index, start_index : stop_index)]

如果想要第2行,第2列和第3列

A_NEW = A[1:2,1:3]

引用numpy索引和切片文章 - Indexing & Slicing