从numpy数组中选择特定的行和列

问题描述 投票:0回答:4

我有一个26行26列的numpy数组。我想选择除第15行以外的所有行以及除第15列以外的所有列。有没有办法做到这一点?

import numpy as np
a = np.arange(676).reshape((26,26))

第15行b = a [14]

和第15栏

c = a[:,14]

应该从a中删除。

是否有可能通过广播来做到这一点?我不想删除行和列,我不想通过切片我想要的部分和使用vstack来制作新的矩阵,因为我觉得它是一个不太优雅的解决方案。我希望在不更改原始数组的情况下选择除b和c之外的所有其他内容。谢谢

python
4个回答
0
投票
import numpy as np
a = np.arange(676).reshape((26,26))

首先,我们需要定义我们想要的行:

index = np.arange(a.shape[0]) != 14 # all rows but the 15th row

我们可以对列使用相同的索引,因为我们选择相同的行和列,a是方阵

现在我们可以使用np.ix_函数来表示我们想要所有选定的行和列。

a[np.ix_(index, index)] #a.shape =(25, 25)

请注意,[index,index]不起作用,因为只选择对角元素(结果是数组而不是矩阵)


0
投票

您可以使用逻辑索引

 row_index = 26 * [False]
 row_index[15] = True

 column_index = 26 * [True]
 colunn_index[15] = False

 myarray[row_index, column_index]

0
投票

你可以使用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)

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html


0
投票

您可以通过应用条件选择除一个之外的所有行和列。在您的情况下,您可以选择除15th之外的所有行和列

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]

这将选择除第15行之外的所有行和列。

© www.soinside.com 2019 - 2024. All rights reserved.