作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何有效地将相同元素从已排序的 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)
最佳答案
一种方法是获取移位位置,即数字发生变化的位置,并使用这些索引将输入数组拆分为子数组。要查找这些索引,您可以使用 np.nonzero
在差异化数组上,然后使用 np.split
用于拆分,就像这样 -
np.split(a,np.nonzero(np.diff(a))[0]+1)
sample 运行-
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])]
关于python - 如何将numpy数组中的相同元素移动到子数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33308738/
我是一名优秀的程序员,十分优秀!