简体   繁体   English

NumPy数组索引

[英]NumPy array indexing

I want to extract the second and the 3rd to the fifth columns of the NumPy array, how would I go about it? 我想提取NumPy数组的第二列,第三列到第五列,我将如何处理?

A = array([[0, 1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 4, 5, 6]])
A[:, [1, 4:6]]

This obviously doesn't work. 这显然行不通。

Assuming I've understood you -- it's usually a good idea to explicitly specify the output you want, because it's not obvious -- you could use numpy.r_ : 假设我已经了解您了-明确指定所需的输出通常是一个好主意,因为它并不明显-您可以使用numpy.r_

In [27]: A
Out[27]: 
array([[0, 1, 2, 3, 4, 5, 6],
       [4, 5, 6, 7, 4, 5, 6]])

In [28]: A[:, [1,3,4,5]]
Out[28]: 
array([[1, 3, 4, 5],
       [5, 7, 4, 5]])

In [29]: A[:, r_[1, 3:6]]
Out[29]: 
array([[1, 3, 4, 5],
       [5, 7, 4, 5]])

In [37]: A[1:, r_[1, 3:6]]
Out[37]: array([[5, 7, 4, 5]])

which you can then flatten or reshape as you like. 然后您可以根据需要展平或重塑。 r_ is basically a convenience function to generate the right indices, eg r_基本上是一个方便的函数,用于生成正确的索引,例如

In [30]: r_[1, 3:6]
Out[30]: array([1, 3, 4, 5])

Perhaps you are looking for this? 也许您正在寻找?

In [10]: A[1:, [1]+range(3,6)]
Out[10]: array([[5, 7, 4, 5]])

Note this gives you the second, fourth, fifth and six columns of all rows but the first. 请注意,这将为您提供除第一行外的所有行的第二,第四,第五和第六列。

The second element is A[:,1] . 第二个元素是A[:,1] Elements 3-5 (I'm assuming you want inclusive) are A[:,2:5] . 元素3-5(假设您要包含在内)是A[:,2:5] You won't be able to extract them with a single call. 您将无法通过一个呼叫提取它们。 To get them as an array, you could do 要将它们作为数组,您可以执行

import numpy as np

A = np.array([[0, 1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 4, 5, 6]])
my_cols = np.hstack((A[:,1][...,np.newaxis], A[:,2:5]))

The np.newaxis stuff is just to make A[:,1] a 2D array, consistent with A[:,2:5] . np.newaxis东西只是使A[:,1]成为2D数组,与A[:,2:5]

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM