组2D numpy数组元素具有相等的第一列值 [英] Group 2D numpy array elements which have equal 1st column values

查看:200
本文介绍了组2D numpy数组元素具有相等的第一列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的二维numpy数组

I have a 2D numpy array like this

[[ 569  897]
 [ 570  898]
 [ 570  900]
 [ 571  901]
 [ 571  905]
 [ 572  906]]

我希望通过以下方式将在第一列中具有相同值的元素分组.

I want the elements which have equal values in the first column to be grouped together in the following way.

[[  569  897]
 [[ 570  898]
  [ 570  900]]
 [[ 571  901]
  [ 571  905]]
 [  572  906] ]

我应该怎么做?

推荐答案

您可以使用np.unique获取分离索引,然后使用np.split进行实际拆分-

You can use np.unique to get the separating indices and then use np.split to actually split -

np.split(a, np.unique(a[:,0], return_index=1)[1][1:],axis=0)

或者,切片,并使用np.flatnonzero-

np.split(a, np.flatnonzero(a[1:,0] != a[:-1,0])+1,axis=0)

样品运行-

In [63]: a
Out[63]: 
array([[569, 897],
       [570, 898],
       [570, 900],
       [571, 901],
       [571, 905],
       [572, 906]])

In [64]: out = np.split(a, np.flatnonzero(a[1:,0] != a[:-1,0])+1,axis=0)

In [65]: out[0]
Out[65]: array([[569, 897]])

In [66]: out[1]
Out[66]: 
array([[570, 898],
       [570, 900]])

In [67]: out[2]
Out[67]: 
array([[571, 901],
       [571, 905]])

In [68]: out[3]
Out[68]: array([[572, 906]])

这篇关于组2D numpy数组元素具有相等的第一列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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