I have implemented and algorithm to remove some columns and rows from an ndarray in Python 2.7, however I feel there should be a better way to do it. Probably I do not know how to do it well in Python, this is why I put the questions here. I have been searching but I have been not succesful finding similar questions and in the documentation (for example in slicing and indexing documentation from scipy)
Assume I have a ndarray with some rows and columns:
number_of_rows = 3
number_of_columns = 3
a = np.arange(number_of_rows*number_of_columns).reshape(number_of_rows,number_of_columns)
a
Which output is:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
Let's supposse I want to remove some columns and/or rows of the previous ndarray. In particular I want to remove column 0 and row 1, this is an output like:
array([[1, 2],
[7, 8]])
To do that I follow the following steps, however they look too me not very elegant and I feel they should be a better implementation.
I select to columns and rows to remove, in this example:
rows_to_remove = [1] columns_to_remove = [0]
Now I create a couple of list with the columns and rows to keep.
rows_to_keep = list(set(range(0,a.shape[0]))-set(rows_to_remove)) columns_to_keep = list(set(range(0,a.shape[1]))-set(columns_to_remove))
This step in Matlab will be simpler just by using ~ to slice the indexes of the matrix (in python ndarray). Is there a better way to do this?.
Then I select those columns and rows to keep:
a[rows_to_keep,:][:,columns_to_keep]
Output:
array([[1, 2],
[7, 8]])
Please note that if you just write:
a[rows_to_keep,columns_to_keep]
which output is:
array([1, 8])
This is a little bit socking for me, that a[rows_to_keep,columns_to_keep]
is different to a[rows_to_keep,:][:,columns_to_keep]
.
Is there a better way to cover those steps?
Thank you very much