如何通过列索引列表对numpy数组进行切片

nev*_*int 2 python numpy slice

我有以下(4x8)numpy数组:

In [5]: z
Out[5]: 
array([['1A34', 'RBP', 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
       ['1A9N', 'RBP', 0.0456267, 0.0539268, 0.331932, 0.0464031,
        4.41336e-06, 0.522107],
       ['1AQ3', 'RBP', 0.0444479, 0.201112, 0.268581, 0.0049757,
        1.28505e-12, 0.480883],
       ['1AQ4', 'RBP', 0.0177232, 0.363746, 0.308995, 0.00169861, 0.0,
        0.307837]], dtype=object)

In [6]: z.shape
Out[6]: (4, 8)
Run Code Online (Sandbox Code Playgroud)

我想要做的是提取上述数组的第0、2和4列,产生(4 x 3)数组,如下所示:

    array([['1A34', 0.0,  0.0],
           ['1A9N', 0.0456267,  0.331932],
           ['1AQ3', 0.0444479, 0.268581],
           ['1AQ4', 0.0177232,  0.308995]])
Run Code Online (Sandbox Code Playgroud)

怎么做呢?请注意,以上索引仅是示例。实际上,它可以是非常不规则的,例如0th,3rd,4th。

Ash*_*ary 6

使用切片:

>>> arr = np.array([['1A34', 'RBP', 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
       ['1A9N', 'RBP', 0.0456267, 0.0539268, 0.331932, 0.0464031,
        4.41336e-06, 0.522107],
       ['1AQ3', 'RBP', 0.0444479, 0.201112, 0.268581, 0.0049757,
        1.28505e-12, 0.480883],
       ['1AQ4', 'RBP', 0.0177232, 0.363746, 0.308995, 0.00169861, 0.0,
        0.307837]], dtype=object)
>>> arr[:,:5:2]
array([['1A34', 0.0, 0.0],
       ['1A9N', 0.0456267, 0.331932],
       ['1AQ3', 0.0444479, 0.268581],
       ['1AQ4', 0.0177232, 0.308995]], dtype=object)
Run Code Online (Sandbox Code Playgroud)

如果列索引不规则,则可以执行以下操作:

>>> indices = [0, 3, 4]
>>> arr[:, indices]
array([['1A34', 1.0, 0.0],
       ['1A9N', 0.0539268, 0.331932],
       ['1AQ3', 0.201112, 0.268581],
       ['1AQ4', 0.363746, 0.308995]], dtype=object)
Run Code Online (Sandbox Code Playgroud)