Why is numpy's behavior different if I slice out only 1 column vs. if I slice out multiple columns?

Viewed 73

If I have a numpy array called data, for example:

[[  3.6216    8.6661   -2.8073   -0.44699   0.     ]
[  4.5459    8.1674   -2.4586   -1.4621    0.     ]
[  3.866    -2.6383    1.9242    0.10645   0.     ]]

and I want to get the last column, I can slice it out by doing:

data[:,4]

However, the output gets "flattened" automatically:

[0. 0. 0]

My expectation was that it should be giving me this instead:

[[0]
 [0]
 [0]]

I know I can easily reshape this, but I would like to understand why numpy is flattening this automatically when I select ONE column. If I select multiple columns instead:

data[:,:4]

I get what I expect:

[[  3.6216    8.6661   -2.8073   -0.44699]
 [  4.5459    8.1674   -2.4586   -1.4621 ]
 [  3.866    -2.6383    1.9242    0.10645]]

Why is numpy's behavior different if I slice out only 1 column vs. if I slice out multiple columns? Is there any way to make numpy's behavior for slicing out 1 column NOT flatten the array?

1 Answers

When you index using a single number, the dimension is eliminated. That's just how NumPy is designed. So this:

data[:,4]

Means "Give me column 4, and reduce the number of dimensions by 1." Whereas this:

data[:,4:5]

Means "Give me column 4, but keep the number of dimensions unchanged."

Related