脾气暴躁的广播 [英] Numpy broadcasting

查看:82
本文介绍了脾气暴躁的广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码提供了数组c的第一行中(0-11)中的元素出现的次数. (a == c [0]).我该如何调整此代码,以便它对c中的所有行都执行相同的操作,而不仅仅是c [0].本质上是for循环.

The following code gives me how many times the elements in a (0-11) occur in the first row of array c. (a==c[0]). How can I adjust this code so it also does the same for all rows in c, not just c[0]. Essentially a for loop.

import numpy as np
c=(np.random.rand(2,5)*12).round()
print (c)

a=np.arange(12).reshape(12,1)
print (np.sum(a==c[0],axis=1))

结果应如下所示,但没有for循环:

The result should look like this, but without the for loop:

for n in range(2):
    a=np.arange(12).reshape(12,1)
    print (np.sum(a==c[n],axis=1))

推荐答案

如果必须使用

If you must use broadcasting that would incur heavy memory usage, you could do -

(c[...,None] == np.arange(12)).sum(1)

对于较大的c,更好的方法是不打扰c,而只是在np.arange(12)周围移动,就像这样-

For bigger sized c, a better way would be to not disturb c and just move around np.arange(12), like so -

(c == (np.arange(12)[:,None,None])).sum(-1).T

以下是有关理论-

In [28]: c=(np.random.rand(2000,5000)*12).round()

In [29]: %timeit (c[...,None] == np.arange(12)).sum(1)
1 loops, best of 3: 423 ms per loop

In [30]: %timeit (c == (np.arange(12)[:,None,None])).sum(-1).T
1 loops, best of 3: 232 ms per loop

这篇关于脾气暴躁的广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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