Home > Mobile >  Remove the columns which have special condition in array
Remove the columns which have special condition in array

Time:03-17

I have an numpy array which has a lot of column, here I only show an small example of it as

 a = np.array(
 [[1, 3 ,4, 5],
 [2, 4 ,7, 8], 
 [2, 7 ,9, 5], 
 [2, 96 ,8, 5]])

I want to delete the columns which the third row is 7 and last row is 96. Here for example, the second column has this condition. The desired output is:

a = np.array(
[[1 ,4, 5],
[2 ,7, 8],
[2 ,9, 5], 
[2 ,8, 5] ])

Thank you in advance

CodePudding user response:

Use boolean slicing:

a2 = a[:,(a[2]!=7)|(a[-1]!=96)]

Or with the reverse operation (De Morgan's Law):

a2 = a[:,~((a[2]==7)&(a[-1]==96))]

Output:

array([[1, 4, 5],
       [2, 7, 8],
       [2, 9, 5],
       [2, 8, 5]])

CodePudding user response:

To find the index of the column that has 7 in the 3rd row and 96 in the fourth row, use argmax with some conditions (since True is 1 and False is 0, argmax will return the index of the first True), and use np.delete with axis=1 to remove it:

indexes = np.where((a[2] == 7) & (a[3] == 96))[0]
a = np.delete(a, indexes, axis=1)

Output:

>>> a
array([[1, 4, 5],
       [2, 7, 8],
       [2, 9, 5],
       [2, 8, 5]])
  • Related