python - numpy array slicing, why sometimes 2-d array and sometimes 1-d array -


my question array slicing in numpy. what's logic following behavior?

x = arange(25) x.shape = (5, 5) # results in 2-d array in rows , columns excerpted x y = x[0:2, 0:2] # results in 1-d array y2 = x[0:2, 0] 

i have expected y2 2-d array contains values in rows 0 , 1, column 0.

this follows standard python conventions. @ results of these analogous expressions:

>>> = [0, 1, 2, 3, 4, 5] >>> a[4] 4 >>> a[4:5] [4] 

as can see, 1 returns one item, while other returns a list containing 1 item. way python works, , numpy following convention, @ higher dimension. whenever pass slice rather individual item, list returned; true if there no items in list, either because end index low, or because starting index high:

>>> a[4:4] [] >>> a[6:6] [] 

so in situations, passing slice means "return sequence (along given dimension)," while passing integer means "return single item (along given dimension)."


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -