Santhosh Subramanian
Santhosh Subramanian

Reputation: 29

How to remove a column from a numpy array if the column has a specified element? (Python)

For example, I have a 2D Array with dimensions 3 x 3.

 [1 2 7

  4 5 6

  7 8 9]

And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of:

 [2

  5

  8]

How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions.

Thank You!

Upvotes: 1

Views: 78

Answers (5)

praneet drolia
praneet drolia

Reputation: 671

A = np.array([[1,2,7],[4,5,6],[7,8,9]])
for i in range(0,3):
...  B=A[:,i]
...  if(7 in B):
...   A=np.delete(A,i,1)

Upvotes: 0

Daniel F
Daniel F

Reputation: 14399

If you don't actually want to delete parts of the original matrix, you can just use boolean indexing:

a
Out[]: 
array([[1, 2, 7],
       [4, 5, 6],
       [7, 8, 9]])

a[:, ~np.any(a == 7, axis = 1)]

Out[]: 
array([[2],
       [5],
       [8]])

Upvotes: 1

R.A.Munna
R.A.Munna

Reputation: 1709

you can use argwhere for column index and then delete.

import numpy
a = numpy.array([[5, 2, 4],[1, 7, 3],[1, 2, 7]])
index = numpy.argwhere(a==7)
y = numpy.delete(a, index, axis=1)
print(y)

Upvotes: 0

Sayali Sonawane
Sayali Sonawane

Reputation: 12599

#Creating array
x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]])

x
Out[]: 
array([[1, 2, 7],
       [4, 5, 6],
       [7, 8, 9]])

#Deletion
a = np.delete(x,np.where(x ==7),axis=1)

a
Out[]: 
array([[2],
       [5],
       [8]])

Upvotes: 3

hiro protagonist
hiro protagonist

Reputation: 46859

numpy can help you do this!

import numpy as np
a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3))
b = np.array([col for col in a.T if 7 not in col]).T
print(b)

Upvotes: 1

Related Questions