是否有按功能分组的numpy? [英] Is there any numpy group by function?

查看:100
本文介绍了是否有按功能分组的numpy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy中是否有任何函数可以按第一列在下面将此数组分组?

Is there any function in numpy to group this array down below by the first column?

我在互联网上找不到任何好的答案.

I couldn't find any good answer over the internet..

>>> a
array([[  1, 275],
       [  1, 441],
       [  1, 494],
       [  1, 593],
       [  2, 679],
       [  2, 533],
       [  2, 686],
       [  3, 559],
       [  3, 219],
       [  3, 455],
       [  4, 605],
       [  4, 468],
       [  4, 692],
       [  4, 613]])

想要的输出:

array([[[275, 441, 494, 593]],
       [[679, 533, 686]],
       [[559, 219, 455]],
       [[605, 468, 692, 613]]], dtype=object)

推荐答案

受Eelco Hoogendoorn的库启发,但没有他的库,并使用了数组第一列一直在增加的事实.

Inspired by Eelco Hoogendoorn's library, but without his library, and using the fact that the first column of your array is always increasing.

>>> np.split(a[:, 1], np.cumsum(np.unique(a[:, 0], return_counts=True)[1])[:-1])
[array([275, 441, 494, 593]),
 array([679, 533, 686]),
 array([559, 219, 455]),
 array([605, 468, 692, 613])]

我没有超时",但这可能是解决问题的更快方法:

I didn't "timeit" but this is probably the faster way to achieve the question :

  • 没有python本机循环
  • 结果列表是numpy数组,如果您需要对其进行其他numpy操作,则无需进行新的转换
  • 像O(n)这样的复杂性

PS:我写了一条类似的文字,因为我需要对np.nonzero的结果进行分组":

PS: I wrote a similar line because I needed to "group by" the results of np.nonzero:

>>> indexes, values = np.nonzero(...)
>>> np.split(values, np.cumsum(np.unique(indexes, return_counts=True)[1]))

这篇关于是否有按功能分组的numpy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆