-1

Suppose I had a standard numpy array such as

a = np.arange(6).reshape((2,3))

When I subarray the array, by performing such task as

a[1, :]

I will lose dimensionality and it will turn into 1D and print, array([3, 4, 5]) Of course the list being 2D you originally want to keep dimensionality. So Ihave to do a tedious task such as

b=a[1, :]
b.reshape(1, b.size)

Why does numpy decrease dimensionality when subarraying?

What is the best way to keep dimensionality, since a[1, :].reshape(1, a.size) will break?

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
J.Doe
  • 3
  • 2

2 Answers2

3

Just use slicing rather than indexing, and the shape will be preserved:

a[1:2]
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Not sure why this was downvoted. It seems correct unless I'm misunderstanding the question.. – Mark Dec 16 '18 at 08:25
  • @MarkMeyer: It is correct, but there is no intelligence or ethics test as part of the Stack Overflow account creation process, so sometimes you see illegitimate downvotes. Oh well. – John Zwinck Dec 16 '18 at 08:27
  • Indeed, perfect, simple. – Matthieu Brucher Dec 16 '18 at 10:33
  • Actuallly,, I like `a[1, None]` better, especially if the index is not `1` but a more complicated expression. You don't really want to type something like `a[n*m*(k-1) + m*(l-1) + u : n*m*(k-1) + m*(l-1) + u + 1]`, right? – Paul Panzer Dec 16 '18 at 18:53
  • What is the difference between slicing and indexing? – J.Doe Dec 17 '18 at 16:53
  • @J.Doe: Indexing reduces dimensions. – John Zwinck Dec 18 '18 at 00:36
  • @JohnZwinck I mean, what is the difference between the two like in meaning. I tried googling difference between indexing and slicing for Python and get 0 results :/ – J.Doe Dec 19 '18 at 17:24
  • @J.Doe: Imagine you have a list of students. Indexing means "Choose the Nth student." Slicing means "Choose the Nth through Pth students." That's why indexing reduces dimensions but slicing does not. – John Zwinck Dec 20 '18 at 02:31
0

Although I agree with John Zwinck's answer, I wanted to provide an alternative in case, for whatever reason, you are forced into using indexing (instead of slicing).

OP says that "a[1, :].reshape(1, a.size) will break":

You can add dimensions to numpy arrays like this:

b = a[1]
# array([3, 4, 5]
b = a[1][np.newaxis]
# array([[3, 4, 5]])

(Note that np.newaxis is None, but it's a lot more readable to use the np.newaxis)


As pointed out in the comments (@PaulPanzer and @Divakar), there are actually many ways to accomplish this same thing (again, with indexing instead of slicing):

These ones do not make a copy (data changed in each affect a)

a[1, None]
a[1, np.newaxis]
a[1].reshape(1, a.shape[1]) # Use shape, not size

This one does make a copy (data is independent from a)

a[[1]]
Stephen C
  • 1,966
  • 1
  • 16
  • 30