我有以下(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)
我想要的是提取上面数组的第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]])
这样做的方法是什么?请注意,上述索引只是示例。实际上它可能非常不规则,例如0th,3rd,4th。
答案 0 :(得分:4)
使用切片:
>>> 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)
如果列索引不规则,那么你可以这样做:
>>> 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)
答案 1 :(得分:0)
您可以通过以下方式访问numpy数组的列:
阵列[:,COLUMN_NUMBER栏]
要获取特定列的数组,您可以执行以下操作:
z = 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]) #your array here
op_array = array([ [z:,0], z[:,2], z[:,3] ])
op_array将第0列,第2列和第3列作为行。
所以你需要转置它以获得所需格式的输出数组。
op_array.transpose()
op_array现在看起来如下:
op_array([['1A34', 0.0, 0.0],
['1A9N', 0.0456267, 0.331932],
['1AQ3', 0.0444479, 0.268581],
['1AQ4', 0.0177232, 0.308995])