dataframe 将一些列与一个系列相乘

dataframe multiply some columns with a series

我有一个数据框 df1,其中索引是 DatetimeIndex,并且有 5 列,col1、col2、col3、col4、col5。

我有另一个 df2,它具有几乎相等的 datetimeindex(df1 中可能缺少 df1 的某些天)和一个 'Value' 列。

当日期相同时,我想将 df1 乘以 df2 的值。但不是所有列 col1...col5,只有 col1...col4

我看到可以乘以 col1*Value,然后乘以 col2*Value 等等...并组成一个新的数据帧来替换 df1。

有没有更高效的方法?

你可以通过重新索引第二个数据帧使它们具有相同的形状,然后使用数据帧运算符 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)