您可以通过重新索引第二个数据框使它们具有相同的形状,然后使用数据框运算符mul 来实现这一点:
使用日期时间序列创建两个数据框。第二个仅使用工作日来确保我们在两者之间存在差距。将日期设置为索引。
import pandas as pd
# first frame
rng1 = pd.date_range('1/1/2011', periods=90, freq='D')
df1 = pd.DataFrame({'value':range(1,91),'date':rng1})
df1.set_index('date', inplace =True)
# second frame with a business day date index
rng2 = pd.date_range('1/1/2011', periods=90, freq='B')
df2 = pd.DataFrame({'date':rng2})
df2['value_to_multiply'] = range(1-91)
df2.set_index('date', inplace =True)
使用第一帧的索引重新索引第二帧。 Df1 现在将在非工作日的间隙中填充前一个有效观察值。
# reindex the second dataframe to match the first
df2 =df2.reindex(index= df1.index, method = 'ffill')
df1 乘以 df2['value_to_multiply_by']:
# multiple filling nans with 1 to avoid propagating nans
# nans can still exists if there are no valid previous observations such as at the beginning of a dataframe
df1.mul(df2['value_to_multiply_by'].fillna(1), axis=0)