Home > Enterprise >  Numpy: What is the difference between slicing with brackets and with comma?
Numpy: What is the difference between slicing with brackets and with comma?

Time:02-17

What is the difference between [x][y][:] and [x, y, :] in numpy? In my example I want to assign a np.ndarray into another and one way works while the other does not. With the same indices, so i really wonder why. Thanks.

>>> gtfb_fft_hypercube.shape
(187, 42, 96, 1026)
>>> amp_mod_cube.shape
(42, 1025, 187)
>>> gtfb_fft_hypercube[0][0][0][1:] = amp_mod_cube[0][:][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (187,) into shape (1025,)
>>> gtfb_fft_hypercube[0, 0, 0, 1:] = amp_mod_cube[0, :, 0]
>>> 

CodePudding user response:

Each [] is a __getitem__ call (or set in the case of []=).

[:] by itself does nothing. Test that yourself in a small array.

[0][0][0][1:] is equivalent to [0,0,0,1:] (though a tad slower).

[0][:][0] is the equivalent of [0,0] or in this 3d case [0,0,:]. That should be obvious from the error message. It selects on the last dimension, not the middle.

Most of the time, when doing multidimensional array indexing, use the single operation syntax [ , , ,]. And spend more time reading basic numpy documentation, especially the big indexing page

https://numpy.org/doc/stable/user/basics.indexing.html

CodePudding user response:

Completely non-technical explanation follows...

When you do:

gtfb_fft_hypercube[0]

you have kind of "looked up and extracted" the first row of gtfb_fft_hypercube and it is a new "thing/entity" with shape (42, 96, 1026).

When you then do:

gtfb_fft_hypercube[0][0]

you are then taking the first element (by slicing) of that new thing - it s no longer attached to or part of your original gtfb_fft_hypercube, it is just a sliced portion from a list-like thing.


It might be easier with words, but the principle is the same:

sentence = ["The","cat","sat","on","the","mat"]

# Get first word - by looking it up in sentence
firstWord = sentence[0]            # firstWord = "The

# Get first letter of first word
firstLetter = firstWord[0]         # firstLetter = "T"

But now we can't refer to sentence or firstWord via firstLetter because it is a new, detached thing.

  • Related