Pandas:乘以数据帧 [英] Pandas: Multiplying Dataframes
问题描述
我正在尝试将整个数据帧大小为 40 行 * 600 列乘以具有 40 行和仅一列的 pandas.core.series.Series.所以我的目标是将所有行乘以唯一行.它给了我一个错误.
I am trying to multiplicate a whole dataframe size 40 row * 600 columns by a pandas.core.series.Series with 40 row and only one columns. So my goal is to multiply all the rows by the unique row. And it gives me back an error.
operands could not be broadcast together with shapes (23560,) (589,)
[In] df1:
[out]
Index col1
2065-12-20 12 days
2061-10-31 12 days
2045-11-28 70 days
2043-10-31 11 days
2040-07-30 21 days
2049-06-30 64 days
2036-01-31 14 days
[In] df2:
Index col1 col2 etc....
2065-12-20 14 120
2061-10-31 18 800
2045-11-28 19 580
2043-10-31 21 12
2040-07-30 44 21
2049-06-30 1.2 17
2036-01-31 61.8 61
[in] k = df1 * df2
[out] operands could not be broadcast together with shapes (23560,) (589,)
我最终想要
Index col1 col2 etc....
2065-12-20 14*12 120*12
2061-10-31 18*12 800*12
2045-11-28 19*70 580*70
2043-10-31 21*11 12*11
2040-07-30 44*21 21*21
2049-06-30 1.2*64 17*64
2036-01-31 61.8*14 61*61
这可能是非常基本的,但我正在纠结它..是因为我的 df1 是在几天内吗?如何将其转换为常规数字?谢谢
It is probably very basic but I am stugling with it..is it because my df1 is in days? How can I transform it into regular numbers? Thank you
推荐答案
使用 mul 方法在两个 DataFrame 之间执行元素乘法:
Use the mul method to execute an element-wise multiplication between two DataFrames:
k = df1.mul(df2)
如果由于第一个 DataFrame 在几天内包含该列而仍然遇到问题,那么您可以将其转换为 int 或在执行逐元素乘法步骤之前浮动:
If you're still having trouble due to the first DataFrame having the column in days, then you can convert it to an int or float before performing the element-wise multiplication step:
import numpy as np
df1.col1 = (df1.col1.values / np.timedelta64(1, 'D')).astype(int)
这篇关于Pandas:乘以数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!