[英]How to remove columns and rows at certain indexes in numpy, at the same time
我有这样一个方阵:
[[0, 516, 226, 853, 1008, 1729, 346, 1353, 1554, 827, 226, 853, 1729, 1008],
[548, 0, 474, 1292, 1442, 2170, 373, 1801, 1989, 1068, 474, 1292, 2170, 1442],
[428, 466, 0, 1103, 1175, 1998, 226, 1561, 1715, 947, 0, 1103, 1998, 1175],
[663, 1119, 753, 0, 350, 1063, 901, 681, 814, 1111, 753, 0, 1063, 350],
[906, 1395, 1003, 292, 0, 822, 1058, 479, 600, 1518, 1003, 292, 822, 0],
[1488, 1994, 1591, 905, 776, 0, 1746, 603, 405, 1676, 1591, 905, 0, 776],
[521, 357, 226, 1095, 1167, 1987, 0, 1552, 1705, 1051, 226, 1095, 1987, 1167],
[1092, 1590, 1191, 609, 485, 627, 1353, 0, 422, 1583, 1191, 609, 627, 485],
[1334, 1843, 1436, 734, 609, 396, 1562, 421, 0, 1745, 1436, 734, 396, 609],
[858, 1186, 864, 1042, 1229, 1879, 984, 1525, 1759, 0, 864, 1042, 1879, 1229],
[428, 466, 0, 1103, 1175, 1998, 226, 1561, 1715, 947, 0, 1103, 1998, 1175],
[663, 1119, 753, 0, 350, 1063, 901, 681, 814, 1111, 753, 0, 1063, 350],
[1488, 1994, 1591, 905, 776, 0, 1746, 603, 405, 1676, 1591, 905, 0, 776],
[906, 1395, 1003, 292, 0, 822, 1058, 479, 600, 1518, 1003, 292, 822, 0]]
我需要同时删除a1
a2
和a3
索引列和行。 我怎样才能做到这一点? 什么是整洁的方式?
请注意,我需要获得另一个方阵。 应删除同一索引处的行和列。 另请注意,当您删除行/列时,索引会发生偏移。 要么我也需要改变a1
, a2
, a3
或者做一些更聪明的事情。
方阵:
[[10,11,12,13],
[14,15,16,17],
[18,19,20,21],
[22,23,24,25]]
删除第一个和第三个索引,结果是:
[[10,12],
[18,20]]
如果你只想要 numpy 并假设数组总是平方的:
a = np.array([[10,11,12,13],
[14,15,16,17],
[18,19,20,21],
[22,23,24,25]])
valid = [r for r in range(a.shape[0]) if r not in [1,3]]
a[valid][:,valid]
>>>array([[10, 12],
[18, 20]])
在 numpy 中试试这个方法。 np.ix_
为您创建一个网格网格来索引 numpy 数组的列和行。 索引列表可以简单地通过获取set.difference
的行范围与要删除的行/列的索引列表之间的set.difference
来创建 -
sqm = np.array([[10,11,12,13],
[14,15,16,17],
[18,19,20,21],
[22,23,24,25]])
rem = [1,3] #Rows/columns to remove
idx = list(set(range(sqm.shape[0])).difference(rem))
print('Rows/columns to keep:',idx)
output = sqm[np.ix_(idx,idx)]
print(output)
Rows/columns to keep: [0, 2]
array([[10, 12],
[18, 20]])
编辑:下面为方阵 10000X10000 和 ~500 行/列添加了基准测试结果以删除。 (macbook pro 13)
sqm = np.random.random((10000,10000))
rem = np.unique(np.random.randint(0,10000,size=500))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.