jlt199
jlt199

Reputation: 2449

Python Numpy: Extracting a row from an array

I'm trying to extract a row from a Numpy array using

t = T[153,:]

But I'm finding that where the size of T is (17576, 31), the size of t is (31,) - the dimensions don't match!

I need t to have the dimensions (,31) or (1,31) so that I can input it into my function. I've tried taking the transpose, but that didn't work.

Can anyone help me with what should be a simple problem?

Many thanks

Upvotes: 4

Views: 28376

Answers (2)

senderle
senderle

Reputation: 150957

Although this might seem surprising, it's actually 100% idiomatic. Think about what you get when you index a list in Python, and what you get when you slice a list:

>>> l = list(range(10))
>>> l[4]
4
>>> l[4:5]
[4]

Of course we see the same thing in an ordinary 1-d array:

>>> a = numpy.arange(10)
>>> a[4]
4
>>> a[4:5]
array([4])

And so it stands to reason that we'd see the same thing in a 2-d array as well:

>>> a = numpy.arange(25).reshape(5, 5)
>>> a[4]
array([20, 21, 22, 23, 24])
>>> a[4:5]
array([[20, 21, 22, 23, 24]])

The shapes reflect this difference:

>>> a[4].shape
(5,)
>>> a[4:5].shape
(1, 5)

Upvotes: 3

akuiper
akuiper

Reputation: 214927

You can extract the row with a slice notation:

t = T[153:154,:]    # will extract row 153 as a 2d array

Example:

T = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

T[1,:]
# array([5, 6, 7, 8])

T[1,:].shape
# (4,)

T[1:2,:]
# array([[5, 6, 7, 8]])

T[1:2,:].shape
# (1, 4)

Upvotes: 7

Related Questions