0

In following code i want to check the shape of each array afer i use :-1 and -1. I thougt that would be x.shape= [2,4,3] ,y.shape =[2,1,3]. But out put is x.shape= [2,4,3], y.shape=[2,3]. I'm confussed where is the second dimmension of y?

thanks a lot if some friends could help me to figure it out.

#code--
import numpy as np
a = np.random.rand(2,5,3)
print(a)
x = a[:,:-1,:]
y = a[:,-1,:]
print(x.shape)
print(y.shape)

#output
[[[0.18648295 0.45018899 0.37269369]
  [0.28727699 0.74595982 0.24410613]
  [0.73484484 0.62852367 0.71091093]
  [0.82692484 0.93791066 0.31497567]
  [0.5506998  0.3992407  0.55229818]]

 [[0.33900664 0.37279058 0.59162413]
  [0.18841992 0.94866945 0.7417921 ]
  [0.67865254 0.61119384 0.49094303]
  [0.07091689 0.55436234 0.80671508]
  [0.37598695 0.96572699 0.04268124]]]
(2, 4, 3)
(2, 3)

i expect some one could answer my question.your text

  • Are you surprised when you have a 1-dimensional array, you do `arr[1]`, and the output is 0-dimensional instead of 1-dimensional? Same thing here. – user2357112 Jul 30 '23 at 02:15
  • When you use an integer in indexing an array, you get that element of the array, not an array containing that element. When you use a slice (with :), you get an array containing the elements inside. If you want a 3D array of `a` that only contains the last element in the 2nd axis, you can use `a[:,-2:-1,:]` – user2649681 Jul 30 '23 at 02:22
  • thanks a lot . it really work. could you pleased to explain "x = a[:,:-1,:]", which slic will be selected? i think for the second dimmension the first 4 elemets will be selected, is that true? – tangfengsongyu Jul 30 '23 at 02:33
  • If you want to index while retaining the dimensions: `y = a[:,[-1],:]` – mozway Jul 30 '23 at 05:48

0 Answers0