例如,作为标题,我有一个2d的numpy数组,如下图所示,
[[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]]
并且我想根据第一列和第二列中的内容有序地提取这些行,在这种情况下,我想获得3个不同的2d numpy数组,如下所示,
[[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]
和
[[32, 22, 0]]
和
[[34, 34, 1]]
我可以使用numpy中的哪个函数来执行此操作?我认为关键是要区分第一行和第二列的不同行.如果这些列中的元素相同,则将特定的行分类在同一输出数组中.我想编写一个python函数来完成这种工作,因为我可以拥有比上述数组更大的数组.随时给我建议,谢谢.
解决方法:
这是处理许多此类分组的一种方法-
# Sort array based on second column
sorted_a = a[np.argsort(a[:,1])]
# Get shifting indices for first col. Split along axis=0 using those.
shift_idx = np.unique(sorted_a[:,1],return_index=True)[1][1:]
out = np.split(sorted_a,shift_idx)
另外,出于提高性能的目的,我们可以获取shift_idx,如下所示-
shift_idx = np.flatnonzero(sorted_a[1:,1] > sorted_a[:-1,1])+1
样品运行-
In [27]: a
Out[27]:
array([[33, 21, 1],
[33, 21, 2],
[32, 22, 0],
[33, 21, 3],
[34, 34, 1]])
In [28]: sorted_a = a[np.argsort(a[:,1])]
In [29]: np.split(sorted_a,np.unique(sorted_a[:,1],return_index=True)[1][1:])
Out[29]:
[array([[33, 21, 1],
[33, 21, 2],
[33, 21, 3]]), array([[32, 22, 0]]), array([[34, 34, 1]])]
标签:arrays,python,numpy