我有这样一个数据集:
[[0,1],
[0,2],
[0,3],
[0,4],
[1,5],
[1,6],
[1,7],
[2,8],
[2,9]]
我需要删除第一列定义的数据的每个 subview 的第一个元素。所以首先我得到所有在第一列中有 0 的元素,然后删除第一行:[0,1]。然后我在第一列中获取带有 1 的元素并删除第一行 [1,5],下一步我删除 [2,8] 等等。最后,我想要一个这样的数据集:
[[0,2],
[0,3],
[0,4],
[1,6],
[1,7],
[2,9]]
编辑:这可以在 numpy 中完成吗?我的数据集非常大,因此所有元素上的循环至少需要 4 分钟才能完成。
最佳答案
根据要求,numpy
解决方案:
import numpy as np
a = np.array([[0,1], [0,2], [0,3], [0,4], [1,5], [1,6], [1,7], [2,8], [2,9]])
_,i = np.unique(a[:,0], return_index=True)
b = np.delete(a, i, axis=0)
(以上经过编辑以纳入@Jaime 的解决方案,为了后代的缘故,这里是我原来的屏蔽解决方案)
m = np.ones(len(a), dtype=bool)
m[i] = False
b = a[m]
有趣的是,mask 似乎更快:
In [225]: def rem_del(a):
.....: _,i = np.unique(a[:,0], return_index=True)
.....: return np.delete(a, i, axis = 0)
.....:
In [226]: def rem_mask(a):
.....: _,i = np.unique(a[:,0], return_index=True)
.....: m = np.ones(len(a), dtype=bool)
.....: m[i] = False
.....: return a[m]
.....:
In [227]: timeit rem_del(a)
10000 loops, best of 3: 181 us per loop
In [228]: timeit rem_mask(a)
10000 loops, best of 3: 59 us per loop
关于python - 删除矩阵 subview 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15705577/