I have a numpy array with 26 rows and 26 columns. I want to select all rows except row 15 and all columns except column 15. Is there any way to do this?
import numpy as np
a = np.arange(676).reshape((26,26))
the 15th row b = a[14]
and 15th column
c = a[:,14]
should both be removed from a.
Is it possible to do this by broadcasting? I don't want to delete the rows and columns and I don't want to make a new matrix by slicing the part I want and using vstack as i feel it is a less elegant solution. I would love to select everything else except b and c without changing the original array. thanks
You can use logical indexing
row_index = 26 * [False]
row_index[15] = True
column_index = 26 * [True]
colunn_index[15] = False
myarray[row_index, column_index]
You can use delete
:
import numpy as np
a = np.arange(676).reshape((26,26))
new_array = np.delete(a, 14, 0)
new_array = np.delete(new_array, 14, 1)
Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html
You can select all rows and columns except one by applying conditions. In your case you can select all the rows and columns except for the 15
th by
import numpy as np
a = np.arange(676).reshape((26,26))
x = np.arrange(26)
y = np.arrange(26)
c = a[x != 14, :]
c = c[:, y != 14]
This selects all rows and columns except for the 15th one.
import numpy as np
a = np.arange(676).reshape((26,26))
First we need to define which rows we want:
index = np.arange(a.shape[0]) != 14 # all rows but the 15th row
we can use the same index for columns, since we are selecting the same rows and columns, and a is a square matrix
Now we can use np.ix_ function to express that we want all selected row and columns.
a[np.ix_(index, index)] #a.shape =(25, 25)
Note that a[index, index] won't work since only the diagonal elements will be selected (the result is an array not a matrix)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.