Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

python - Numpy - slicing 2d row or column vector from array

I'm trying to find a neat little trick for slicing a row/column from a 2d array and obtaining an array of (col_size x 1) or (1 x row_size).

Is there an easier way than to use numpy.reshape() after every slicing?

Cheers, Stephan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can slice and insert a new axis in one single operation. For example, here's a 2D array:

>>> a = np.arange(1, 7).reshape(2, 3)
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

To slice out a single column (returning array of shape (2, 1)), slice with None as the third dimension:

>>> a[:, 1, None]
array([[2],
       [5]])

To slice out a single row (returning array of shape (1, 3)), slice with None as the second dimension:

>>> a[0, None, :]
array([[1, 2, 3]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...