【问题标题】:Python DataFrame to multiply two time series data framePython DataFrame 将两个时间序列数据框相乘
【发布时间】:2017-08-19 01:20:27
【问题描述】:

我有两个数据框。第一个数据帧有一年的能量,时间间隔为 30 分钟。第二个数据框是 30 分钟的一日价格数据。

如何将两个数据帧相乘以获得第二个数据帧在第一个数据帧的每一天重复相乘的结果?

非常感谢!

【问题讨论】:

  • 为什么不将 df2 扩展到 df1 的大小?
  • 向我们展示您的输入数据和所需输出数据的样本。
  • 欢迎来到 SO!请查看以下内容,以便其他人能够更好地帮助您。 stackoverflow.com/questions/20109391/…

标签: python pandas


【解决方案1】:

您可以按时间合并多个数据帧,首先确保您的日期在两个数据帧的日期时间索引中。

MVCE:

df1 = pd.DataFrame({'kilowatts':np.random.randint(100,1000,(2*24*365))},index=pd.date_range('2016-01-01',periods=(2*24*365),freq='30T'))
df2 = pd.DataFrame({'Dol_per_KW':np.random.rand(48)},index=pd.date_range('2016-01-01',periods = 48,freq='30T'))

在每个数据框中创建时间列以作为合并键。

df1['Time'] = df1.index.time
df2['Time'] = df2.index.time

合并和乘法:

df_out = df1.merge(df2, on='Time',right_index=True)\
            .eval('cost = kilowatts * Dol_per_KW', inplace=False)\
            .sort_index()

让我们打印每天10:00和10:30来验证。

print(df_out.loc[df_out.index.hour == 10].head(10))

输出:

                     kilowatts      Time  Dol_per_KW        cost
2016-01-01 10:00:00        187  10:00:00    0.460365   86.088217
2016-01-01 10:30:00        743  10:30:00    0.572282  425.205644
2016-01-02 10:00:00        364  10:00:00    0.460365  167.572786
2016-01-02 10:30:00        668  10:30:00    0.572282  382.284482
2016-01-03 10:00:00        170  10:00:00    0.460365   78.262016
2016-01-03 10:30:00        682  10:30:00    0.572282  390.296432
2016-01-04 10:00:00        336  10:00:00    0.460365  154.682572
2016-01-04 10:30:00        451  10:30:00    0.572282  258.099254
2016-01-05 10:00:00        215  10:00:00    0.460365   98.978431
2016-01-05 10:30:00        295  10:30:00    0.572282  168.823237

【讨论】:

  • 非常感谢!用DataFrame.mul好像也可以吗?
猜你喜欢
  • 1970-01-01
  • 2020-04-06
  • 2018-01-24
  • 2021-07-31
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
相关资源
最近更新 更多