python如何将数组里的数提取出来_python-如何根据内容从numpy数组中提取行?

例如,作为标题,我有一个2d的numpy数组,如下图所示,

[[33, 21, 1],

[33, 21, 2],

[32, 22, 0],

[33, 21, 3],

[34, 34, 1]]

并且我想根据第一列和第二列中的内容有序地提取这些行,在这种情况下,我想获得3个不同的2d numpy数组,如下所示,

[[33, 21, 1],

[33, 21, 2],

[33, 21, 3]]

[[32, 22, 0]]

[[34, 34, 1]]

我可以使用numpy中的哪个函数来执行此操作?我认为关键是要区分第一行和第二列的不同行.如果这些列中的元素相同,则将特定的行分类在同一输出数组中.我想编写一个python函数来完成这种工作,因为我可以拥有比上述数组更大的数组.随时给我建议,谢谢.

解决方法:

这是处理许多此类分组的一种方法-

# Sort array based on second column

sorted_a = a[np.argsort(a[:,1])]

# Get shifting indices for first col. Split along axis=0 using those.

shift_idx = np.unique(sorted_a[:,1],return_index=True)[1][1:]

out = np.split(sorted_a,shift_idx)

另外,出于提高性能的目的,我们可以获取shift_idx,如下所示-

shift_idx = np.flatnonzero(sorted_a[1:,1] > sorted_a[:-1,1])+1

样品运行-

In [27]: a

Out[27]:

array([[33, 21, 1],

[33, 21, 2],

[32, 22, 0],

[33, 21, 3],

[34, 34, 1]])

In [28]: sorted_a = a[np.argsort(a[:,1])]

In [29]: np.split(sorted_a,np.unique(sorted_a[:,1],return_index=True)[1][1:])

Out[29]:

[array([[33, 21, 1],

[33, 21, 2],

[33, 21, 3]]), array([[32, 22, 0]]), array([[34, 34, 1]])]

标签:arrays,python,numpy

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值