简体   繁体   English

使用 2d numpy 数组广播 1d numpy 数组

[英]Broadcasting a 1d numpy array with a 2d numpy array

This is probably a really simple question, but I am not figuring this out.这可能是一个非常简单的问题,但我没有弄清楚这一点。

I have a 2D numpy array, which is of shape (3,2) and a 1D array of shape (3,):我有一个形状为 (3,2) 的二维 numpy 数组和一个形状为 (3,) 的一维数组:

    A = [[2,4],[6,8][10,12]]
    B = [1,2,4]

I would like to divide array A by array B, resulting in:我想将数组 A 除以数组 B,结果:

   [[2,4],[3,4][2.5,3]]

But numpy will not let me do this, I think because the shape is not right.但是numpy不会让我这样做,我觉得是因为形状不对。 I get the familiar 'operands could not be broadcast together with shapes (10,2) (10,)' error.我得到了熟悉的“操作数无法与形状 (10,2) (10,) 一起广播”错误。

I tried things with reshape and swapaxis, but it is not working.我尝试了 reshape 和 swapaxis 的东西,但它不起作用。 I would much prefer to be able to do this without a for loop (because I need to do this many many times with large arrays) and without having to swap the axis of array A (because other arrays are if this shape).我更希望能够在没有 for 循环的情况下执行此操作(因为我需要使用大数组多次执行此操作)并且不必交换数组 A 的轴(因为其他数组也是这种形状)。

Can you guys help me?你们能帮帮我吗?

Extend B to 2D and then divide -B扩展到2D然后除以 -

A/B[:,None].astype(float)

Sample run -样品运行 -

In [9]: A
Out[9]: 
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])

In [10]: B
Out[10]: array([1, 2, 4])

In [11]: A/B[:,None].astype(float)
Out[11]: 
array([[ 2. ,  4. ],
       [ 3. ,  4. ],
       [ 2.5,  3. ]])

Or use from __future__ import division that takes care of division to result in a floating pt array -或者使用from __future__ import division处理除法以产生浮动 pt 数组 -

In [14]: from __future__ import division

In [15]: A/B[:,None]
Out[15]: 
array([[ 2. ,  4. ],
       [ 3. ,  4. ],
       [ 2.5,  3. ]])

Performance boost with multiplication by reciprocal -乘以倒数提高性能 -

In [32]: A = np.random.rand(300,200)

In [33]: B = np.random.rand(300)

In [34]: from __future__ import division

In [35]: %timeit A/B[:,None]
1000 loops, best of 3: 336 µs per loop

In [36]: %timeit A*(1.0/B[:,None])
10000 loops, best of 3: 101 µs per loop

More info on this could be found here .可以在here找到有关此的更多信息。 Also, one needs to be careful using this method though, if the values of B are extremely close to 0 .此外,如果B的值非常接近0 ,则需要小心使用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM