1

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!

5 Answers 5

3
#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]])
Sign up to request clarification or add additional context in comments.

1 Comment

ah, was looking for a version with where and axis... nice!
1

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)

Comments

1

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]])

Comments

0

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)

Comments

0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.