gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:07:06 24 4
gpt4 key购买 nike

如何有效地将相同元素从已排序的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com