Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete every nth row or column in a matrix using Python

I am trying to delete every 8th column in a 1024x1024 matrix using this method but it takes a lot of time and it will be more difficult when I have to process millions of matrices. Could you please show me how can I delete every nth row or column starting from a certain row or column and using numpy, scipy or any other Python package?

Many thanks

like image 521
ticofiz Avatar asked Mar 08 '15 10:03

ticofiz


People also ask

How do you delete rows and columns in a matrix in python?

Using the NumPy function np. delete() , you can delete any row and column from the NumPy array ndarray . Specify the axis (dimension) and position (row number, column number, etc.). It is also possible to select multiple rows and columns using a slice or a list.

How do you remove the nth element from an array in Python?

To remove every nth element of a list in Python, utilize the Python del keyword to delete elements from the list and slicing. For your slice, you want to pass n for the slice step size.

How do I remove multiple columns from an array in Python?

It returns an array by deleting the elements at given index or indices. Now to remove multiple columns in the array we need to pass the given array and the 'array of index' of the columns to be deleted and axis=1 to the delete() method. Slice() method is used to pass a slice of column indices to the delete() method.


1 Answers

You can use np.delete giving the indices corresponding to every 8th row index. Let a be a 2D array or a matrix:

np.delete(a, list(range(0, a.shape[0], 8)), axis=0)

note the use of axis=0 indicating to operate along the rows. To operate along the columns:

np.delete(a, list(range(0, a.shape[1], 8)), axis=1)
like image 171
Saullo G. P. Castro Avatar answered Sep 30 '22 14:09

Saullo G. P. Castro