如何将numpy数组中的相同元素移动到子数组中

时间:2015-10-23 18:02:16

标签: python numpy itertools

如何有效地将已排序的numpy数组中的相同元素移动到子数组中?

从这里开始:

import numpy as np     
a=np.array([0,0,1,1,1,3,5,5,5])

到这里:

a2=array([[0, 0], [1, 1, 1], [3], [5, 5, 5]], dtype=object)

2 个答案:

答案 0 :(得分:3)

一种方法是获取轮班位置,数字发生变化,并使用这些索引将输入数组拆分为子阵列。要查找这些索引,您可以在区分数组上使用np.nonzero,然后使用np.split进行拆分,就像这样 -

np.split(a,np.nonzero(np.diff(a))[0]+1)

示例运行 -

In [42]: a
Out[42]: array([2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6])

In [43]: np.split(a,np.nonzero(np.diff(a))[0]+1)
Out[43]: 
[array([2, 2, 2, 2]),
 array([3, 3, 3, 3]),
 array([4, 4, 4, 4, 4, 4, 4]),
 array([5, 5]),
 array([6, 6, 6])]

答案 1 :(得分:2)

执行此操作的一种方法是使用itertools.groupby。示例 -

result = np.array([list(g) for _,g in groupby(a)])

这也适用于普通的排序列表,而不仅仅是numpy数组。

演示 -

In [24]: import numpy as np

In [25]: a=np.array([0,0,1,1,1,3,5,5,5])

In [26]: from itertools import groupby

In [27]: result = np.array([list(g) for _,g in groupby(a)])

In [28]: result
Out[28]: array([[0, 0], [1, 1, 1], [3], [5, 5, 5]], dtype=object)

与其他方法的时间比较 -

In [29]: %timeit np.array([list(g) for _,g in groupby(a)])
The slowest run took 6.10 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 9.86 µs per loop

In [30]: %timeit np.split(a,np.where(np.diff(a)>0)[0]+1)
10000 loops, best of 3: 29.2 µs per loop

In [31]: %timeit np.array([list(g) for _,g in groupby(a)])
100000 loops, best of 3: 10.5 µs per loop

In [33]: %timeit np.split(a,np.nonzero(np.diff(a))[0]+1)
The slowest run took 4.32 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 25.2 µs per loop