gpt4 book ai didi

python - 如何通过广播将numpy数组与 Pandas 数据帧相乘

转载 作者:行者123 更新时间:2023-12-04 10:16:41 24 4
gpt4 key购买 nike

我有一个形状为(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

我想将数据框的每一列乘以形状为(4,)的numpy数组:
In [9]: y = np.random.randn(4)

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

在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]])

但是,它在 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)

有什么建议么?

谢谢!

最佳答案

我找到了另一种在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

关于python - 如何通过广播将numpy数组与 Pandas 数据帧相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31970356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com