5

If curr_frames is a numpy array, what does the last line mean?

curr_frames = np.array(curr_frames)

idx = map(int,np.linspace(0,len(curr_frames)-1,80))

curr_frames = curr_frames[idx,:,:,:,]
kentwait
  • 1,969
  • 2
  • 21
  • 42
  • 3
    Welcome to Stack Overflow. You may find it helpful to read [this article](https://stackoverflow.com/help/how-to-ask). The usual format for a question of this type would be to present some code you have run with unexpected results, with descriptions of what happened and what you expected. The answers should help you fix it. You can edit your question (see the link underneath it). – holdenweb Jan 27 '19 at 15:48
  • 3
    The difference is that they are very different. You can read the numpy documentation to see exactly how numpy slicing works. The thing is, in Python, when you implement your classes (as numpy does), you can define slicing to do whatever you want it to do. – zvone Jan 27 '19 at 16:19

2 Answers2

8

An important distinction from Python’s built-in lists to numpy arrays:

  • when slicing in the built-in list it creates a copy.

    X=[1,2,3,4,5,6]
    Y=X[:3]   #[1,2,3]
    

    by slicing X from 0-3 we have created a copy and stored it in the variable Y.

we can verify that by changing the Y and even if we change Y it does not effect X.

    Y[0]=20
    print(Y) # [20,2,3]
    print(X) # [1,2,3,4,5,6]
  • when slicing in numpy doesn't create a new copy but it still referring to original array

    A=np.array([1,2,3,4,5,6])
    B=A[:3]
    

By slicing A here and assigning it to B, still B referring to original array A.

We can verify that by changing an element in B and it will change the value in A as well.

    B[0]=20
    print(B) # [20,2,3]
    print(A) # [20,2,3,4,5,6]
Ravi
  • 2,778
  • 2
  • 20
  • 32
  • 1
    Good point especially if X is very big. Slicing the numpy array vs the list has big speed improvements – Aenaon Mar 01 '20 at 12:04
4

The main difference is that numpy slicing can handle multiple dimensions. In your example, curr_frames[idx,:,:,:,], the array has 4 dimensions and you are slicing by supplying the indices for one dimension (idx) and the : notation means to retrieve all for that dimension.

References:

NumPy slicing

Python slicing

kentwait
  • 1,969
  • 2
  • 21
  • 42