Home > Software design >  How to get the specific out put for Numpy array slicing?
How to get the specific out put for Numpy array slicing?

Time:05-28

x is an array of shape(n_dim,n_row,n_col) of 1st n natural numbers b is boolean array of shape(2,) having elements True,false


    def array_slice(n,n_dim,n_row,n_col):
             x = np.arange(0,n).reshape(n_dim,n_row,n_col)
             b = np.full((2,),True)
             print(x[b])
             print(x[b,:,1:3]) 

expected output

[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]]
[[[ 1  2]
  [ 6  7]
  [11 12]]]

my output:-

[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]
 [[15 16 17 18 19]
  [20 21 22 23 24]
  [25 26 27 28 29]]]
[[[ 1  2]
  [ 6  7]
  [11 12]]
 [[16 17]
  [21 22]
  [26 27]]]

CodePudding user response:

An example:

In [83]: x= np.arange(24).reshape(2,3,4)

In [84]: b = np.full((2,),True)

In [85]: x
Out[85]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

In [86]: b
Out[86]: array([ True,  True])

With two True, b selects both plains of the 1st dimension:

In [87]: x[b]
Out[87]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

A b with a mix of true and false:

In [88]: b = np.array([True, False])

In [89]: b
Out[89]: array([ True, False])

In [90]: x[b]
Out[90]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]])
  • Related