pandas 如何通过广播将pandas数据帧与numpy数组相乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31970356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:45:35  来源:igfitidea点击:

how to multiply pandas dataframe with numpy array with broadcasting

pythonnumpypandasarray-broadcasting

提问by Wei Li

I have a dataframe of shape (4, 3) as following:

我有一个形状为 (4, 3) 的数据框,如下所示:

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: x = pd.DataFrame(np.random.randn(4, 3), index=np.arange(4))

In [4]: x
Out[4]: 
          0         1         2
0  0.959322  0.099360  1.116337
1 -0.211405 -2.563658 -0.561851
2  0.616312 -1.643927 -0.483673
3  0.235971  0.023823  1.146727

I want to multiply each column of the dataframe with a numpy array of shape (4,):

我想将数据框的每一列与形状为 (4,) 的 numpy 数组相乘:

In [9]: y = np.random.randn(4)

In [10]: y
Out[10]: array([-0.34125522,  1.21567883, -0.12909408,  0.64727577])

In numpy, the following broadcasting trick works:

在 numpy 中,以下广播技巧有效:

In [12]: x.values * y[:, None]
Out[12]: 
array([[-0.32737369, -0.03390716, -0.38095588],
       [-0.25700028, -3.11658448, -0.68303043],
       [-0.07956223,  0.21222123,  0.06243928],
       [ 0.15273815,  0.01541983,  0.74224861]])

However, it doesn't work in the case of pandas dataframe, I get the following error:

但是,它不适用于 Pandas 数据框,出现以下错误:

In [13]: x * y[:, None]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-21d033742c49> in <module>()
----> 1 x * y[:, None]
...
ValueError: Shape of passed values is (1, 4), indices imply (3, 4)

Any suggestions?

有什么建议?

Thanks!

谢谢!

回答by Wei Li

I find an alternative way to do the multiplication between pandas dataframe and numpy array.

我找到了一种替代方法来在 pandas 数据帧和 numpy 数组之间进行乘法。

In [14]: x.multiply(y, axis=0)
Out[14]: 
          0         1         2
0  0.195346  0.443061  1.219465
1  0.194664  0.242829  0.180010
2  0.803349  0.091412  0.098843
3  0.365711 -0.388115  0.018941

回答by dagrha

I think you are better off using the df.apply()method. In your case:

我认为您最好使用df.apply()方法。在你的情况下:

x.apply(lambda x: x * y)