简体   繁体   English

二维 ndarray:逐行操作

[英]2D ndarray: row-wise operations

I have 2D numpy array, with example shape:我有二维 numpy 数组,示例形状:

>>> a.shape
(48, 160)

and I want to do simple operation between elements or each row, like a[0] - a[1] but for every row against all other rows.我想在元素或每一行之间做简单的操作,比如a[0] - a[1]但对于所有其他行的每一行。

I know how to do it simply by using for loop and iterating rows, but I was wondering if there is some numpy slicing specific instruction, that can do this without using for loops我知道如何简单地通过使用for循环和迭代行来做到这一点,但我想知道是否有一些 numpy 切片特定指令,可以在不使用for循环的情况下做到这一点

You can use broadcasting magic to do this.您可以使用广播魔法来做到这一点。

import numpy as np
a = np.arange(12).reshape((4, 3))
b = np.arange(15).reshape((5, 3))
diff = a[np.newaxis, :, :] - b[:, np.newaxis, :]
diff.shape
# (5, 4, 3)

This is a good broadcasting tutorial.是一个很好的广播教程。 In this case I make a (1, 4, 3) and b (5, 1, 3) and I get a result that's (5, 4, 3), the difference of every row pair in a and b.在这种情况下,我生成 a (1, 4, 3) 和 b (5, 1, 3) 并且得到的结果是 (5, 4, 3),即 a 和 b 中每一行对的差值。

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

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