Home > front end >  access numpy array row by index
access numpy array row by index

Time:01-07


    x=np.array([[6.99, 0, 3],
                [7, 9, 3],
                [2, 4, 7]])
    
    a = np.round(np.diff(x[:,0]),2)
    print(x)
    c1 = a == 0   
    c2 = a == 0.01
    c3 = a == -0.01
    mask = c1| c2 | c3
    print(mask)
    
    indices = np.nonzero(mask)[0]  
    print(indices) # prints[0] <----


want to print row at index 0 and 1 i.e indices,indices 1 because these are the rows where my conditions are matching so i am doing


    common = x[[indices,indices 1],:] # it works as there is only one value in indices 
    print(common)
    
    output = 
    
    [[[6.99 0.   3.  ]]
     [[7.   9.   3.  ]]]

output expected - row 0,1 and it is working as expected


but does not works if there are multiple values in indices 

x=np.array([[6.99, 0, 3],
            [7, 9, 3],
            [2, 8, 3],
            [2, 4, 7]])

a = np.round(np.diff(x[:,0]),2)
print(x)
c1 = a == 0   
c2 = a == 0.01
c3 = a == -0.01
mask = c1| c2 | c3
print(mask)

indices = np.nonzero(mask)[0]  
print(indices) #prints [0 2] <------------



common = x[[indices,indices 1],:]
print(common)

output is  - 

[[[6.99 0.   3.  ]
  [2.   8.   3.  ]]

 [[7.   9.   3.  ]
  [2.   4.   7.  ]]]

output expected - row 0,1,2,3 ,the array as it is ,
using for loop it is working but i dont want to use it

CodePudding user response:

In the first example:

In [48]:     x=np.array([[6.99, 0, 3],
    ...:                 [7, 9, 3],
    ...:                 [2, 4, 7]])
    ...: 
    ...:     a = np.round(np.diff(x[:,0]),2)
    ...:     c1 = a == 0
    ...:     c2 = a == 0.01
    ...:     c3 = a == -0.01
    ...:     mask = c1| c2 | c3
In [49]: x
Out[49]: 
array([[6.99, 0.  , 3.  ],
       [7.  , 9.  , 3.  ],
       [2.  , 4.  , 7.  ]])
In [50]: a
Out[50]: array([ 0.01, -5.  ])
In [51]: mask
Out[51]: array([ True, False])
In [52]: np.nonzero(mask)
Out[52]: (array([0]),)

a and mask are 2 element, 1d arrays.

In the second:

In [54]: x
Out[54]: 
array([[6.99, 0.  , 3.  ],
       [7.  , 9.  , 3.  ],
       [2.  , 8.  , 3.  ],
       [2.  , 4.  , 7.  ]])
In [55]: a
Out[55]: array([ 0.01, -5.  ,  0.  ])
In [56]: mask
Out[56]: array([ True, False,  True])
In [57]: np.nonzero(mask)
Out[57]: (array([0, 2]),)

Your list of indices is actually used as though it were an array. It indexing the 1st dim of x with a (2,2) array, resulting in a (2,2,3) array

In [58]: indices = np.nonzero(mask)[0]
In [59]: [indices,indices 1]
Out[59]: [array([0, 2]), array([1, 3])]
In [60]: np.array([indices,indices 1])
Out[60]: 
array([[0, 2],
       [1, 3]])

You could transpose and ravel to get the desired 1d array of indices:

In [61]: np.array([indices,indices 1]).T.ravel()
Out[61]: array([0, 1, 2, 3])
  •  Tags:  
  • Related