1

I have an array z = np.array([[1,2,3], [4,5,6]]) which has the shape (2, 3). Within one column there is one x and one y value. I want to retrieve the values of one column print(z[:, 2]. However, instead of outputting a (2,1) shape, I get a (1,2) shape.

The output I got:

[3 6]

The output I expect:

[[3]
 [6]]

The thing is, I want to add z[:, 2] to another variable of the shape (2,1). What am I missing? And how can I achieve my goal? Thanks a lot in advance.

rdas
  • 20,604
  • 6
  • 33
  • 46
Mino
  • 25
  • 3
  • 1
    Sorry, I misread. Let me try again. `I get a (1,2) shape.` No, you don't - you get a `(2,)` shape (i.e., 1-dimensional). That is because using an integer in the slice *reduces the dimensions* of the slice - in the same way that if you index into an ordinary Python list, you get *one of the elements*, instead of a list with one element in it. The problem is solved *in the same way*: slice that dimension, rather than indexing it. The necessary slice is formed *in the same way*: as a `x:x+1` range. (There are other ways as well.) – Karl Knechtel May 19 '22 at 14:12

1 Answers1

2

You need to slice with a 2D selector:

z[:, [2]]

output:

array([[3],
       [6]])
mozway
  • 194,879
  • 13
  • 39
  • 75