python中多维数组的计算_计算python中多维数组中数组的出现次数

可以将这些行转换为1D数组,使用元素作为二维索引,并使用^{}。然后,使用^{}给我们每个唯一行的开始位置,并且还有一个可选参数return_counts来给我们计数。因此,实现将如下所示-def unique_rows_counts(a):

# Calculate linear indices using rows from a

lidx = np.ravel_multi_index(a.T,a.max(0)+1 )

# Get the unique indices and their counts

_, unq_idx, counts = np.unique(lidx, return_index = True, return_counts=True)

# return the unique groups from a and their respective counts

return a[unq_idx], counts

样本运行-

^{pr2}$

标杆管理

假设您可以将numpy数组或集合作为输出,那么可以对迄今为止提供的解决方案进行基准测试,如下-

功能定义:import numpy as np

from collections import Counter

def unique_rows_counts(a):

lidx = np.ravel_multi_index(a.T,a.max(0)+1 )

_, unq_idx, counts = np.unique(lidx, return_index = True, return_counts=True)

return a[unq_idx], counts

def map_Counter(a):

return Counter(map(tuple, a))

def forloop_Counter(a):

c = Counter()

for x in a:

c[tuple(x)] += 1

return c

时间安排:In [53]: a = np.random.randint(0,4,(10000,5))

In [54]: %timeit map_Counter(a)

10 loops, best of 3: 31.7 ms per loop

In [55]: %timeit forloop_Counter(a)

10 loops, best of 3: 45.4 ms per loop

In [56]: %timeit unique_rows_counts(a)

1000 loops, best of 3: 1.72 ms per loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值