When I use [[]] as my index number, why does it return this?

Viewed 61

I'm a beginner in python so this might be a very dumb question:

So I was playing around with how people directly access an array.

I created an array array = np.array([2,3,4])

When I was trying to access it, instead of saying print(array[1])

I said print(array[[1]]) and it outputted [3] instead of just saying 3.

Why is that? I think this could be related to how in dataframes people use [[]] to access categories but I'm not really sure about the connection here.

Also if possible, can someone please explain in simple terms what is the computer actually doing when people use [[]].

I have tried to check the pandas documentation but I seriously don't understand it because I'm only a beginner in python.

1 Answers

What you are doing there is extracting an array of elements from the array rather than just a single element. It just happens that you are getting an array of length one.

To understand better, try this:

import numpy as np
a = np.array([2,3,4])
print(a[1])
print(a[2])
print(a[[1]])
print(a[[1,2,0,2,1]])

You should get

3
4
array([3])
array([3,4,2,4,3])

and hopefully you can see that the [[1]] case that you've tried is just a special case of the last example that I've added.

If that's still not clear, perhaps you could try this:

a = np.array([2,3,4])
indices = [1,2,0,2,1]
print(a[indices])

which is the same thing, but might look more sensible to you. It's the difference between asking for the value at an index and asking for the values at a collection of indices. Both are possible with numpy.

Note also that this functionality is specific to numpy (and pandas), and does not work on regular Python lists:

a = [2,3,4]
print(a[1])  # => 3
print(a[[1]])  # => TypeError
Related