difference between A[0] and A[0:1] numpy arrays in python

  • A+
Category:Languages

I have a numpy array like this:

candidates =   array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,         0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],        [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,         0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1],        [1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,         0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0]]) 

And I do not understand what is the difference between candidates[0]:

candidates[0] =   array([1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,        0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]  candidates[0].shape = (34,) 

And candidates[0:1]:

candidates[0:1] =   array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,         0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]])  candidates[0:1].shape = (1, 34) 

because I believe the two should give the exact same results? I mean the later i.e. candidates[0:1] is supposed to represent the first element only, right? So, what is the difference between the two exactly?


In Python, [0] is indexing—it returns the first element, while [0:1] is slicing—it returns a collection of all of the first 1 elements.

This may be easier to see with a plain old list:

>>> lst = [1, 2, 3] >>> lst[0] 1 >>> lst[0:1] [1] 

Numpy extends Python indexing and slicing, and some of these would give you a 2D result, for different reasons—e.g., you could index with [0] as an “array-like”, which would work as an index array), but the relevant basics are the same here. For a 2D numpy array, the elements are rows, so candidates[0] is the first row—a 1D array, while candidates[0:1] is an array of all of the first 1 rows—a 2D array. So the first one has shape (34,), and the second has shape (1, 34).

The difference may not be obvious if you don't look closely, but compare how the two start:

array([1, array([[1, 

They're not lined up, because the second one has two brackets instead of one, which is because it's a 2D array instead of 1D.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: