简体   繁体   English

如何在numpy中求和2d和1d数组?

[英]How to sum 2d and 1d arrays in numpy?

Supposing I have 2d and 1d numpy array. 假设我有2d和1d numpy数组。 I want to add the second array to each subarray of the first one and to get a new 2d array as the result. 我想将第二个数组添加到第一个的每个子数组,并得到一个新的2d数组作为结果。

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> b = np.array([2, 3])
>>> c = ... # <-- What should be here?
>>> c
array([[3, 5],
       [5, 7],
       [7, 9],
       [9, 22]])

I could use a loop but I think there're standard ways to do it within numpy. 我可以使用循环,但我认为在numpy中有标准的方法可以执行此循环。

What is the best and quickest way to do it? 最好和最快的方法是什么? Performance matters. 性能很重要。

Thanks. 谢谢。

I think the comments are missing the explanation of why a+b works. 我认为这些评论缺少对a + b起作用的解释。 It's called broadcasting 叫做广播

Basically if you have a NxM matrix and a Nx1 vector, you can directly use the + operator to "add the vector to each row of the matrix. 基本上,如果您有NxM矩阵和Nx1向量,则可以直接使用+运算符“将向量添加到矩阵的每一行。

This also works if you have a 1xM vector and want to add it columnwise. 如果您有一个1xM的向量并想逐列添加,这也可以使用。

Broadcasting also works with other operators and other Matrix dimensions. 广播还可以与其他运营商和其他矩阵维度一起使用。

Take a look at the documentation to fully understand broadcasting 查看文档以充分了解广播

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

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