Skip to main content
  1. About
  2. For Teams
Asked
Viewed 30k times
4

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

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this is the type of area where I'm finding conversion from Matlab difficult
3

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)

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.