0

I have a matrix with 3 dimension:

import numpy as np
a = np.array([[['Mon',18,20,22,17],['Tue',11,18,21,18]],
   [['Wed',15,21,20,19],['Thu',11,20,22,21]],
   [['Fri',18,17,23,22],['Sat',12,22,20,18]]])**

and if I do

print(a[0,1,3]) and print(a[0][1][3])

they return the same result.

but if I do:

print(a[:,1,3])
print(a[:][1][3])

I obtain the following error

> ---------------------------------------------------------------------------
> IndexError  Traceback (most recent call last)
/var/folders/1l/3t6_gr9d461945kx872yt9rm0000gn/T/ipykernel_1070/3758069636.py in <module>
      7 print(np.shape(a))
      8 print((a[:,1,3]))
----> 9 print((a[:][1][3]))
> 
> IndexError: index 3 is out of bounds for axis 0 with size 2

what is the differences between a[:][1][3] and a[:,1,3])?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 2
    a[:] is the original array – asimoneau Oct 18 '21 at 18:34
  • 2
    If you have the array [1,2,3]. `arr[:]` returns `[1,2,3]`, which is exactly the same array, and future indexing will start with the 0th dimension. So `arr[:][:][:][:][3]` will return 3. If you want to take advantage of Numpy's indexing features, put it all in one set of square brackets with commas. – Kaia Oct 18 '21 at 18:35
  • keep in mind this is discussing custom slicing behavior specific to numpy. Many of the things discussed here are not valid slice notation for a list of lists or tuple of tuples for example. – Aaron Oct 18 '21 at 18:39
  • I like to think of it like there's an implicit ellipsis `...` after each slice: `arr[:, ...]` whenever you don't specify an index for each dimension. Ellipsis basically expands to `:` for all the dimensions that are left, so the line that errored would expand to: `arr[:, :, :][1, :, :][3, :]`. The first slice just returns the entire array, the second slice returns the second element along the first axis (wed/thur row), and the third slice attempts to take the 4th element along the second axis (which is an error because there are only 2 elements) – Aaron Oct 18 '21 at 18:51

0 Answers0