我有一个数据框,它包含每天的客户余额。示例数据如下所示:
Pstng Date DailyCustomerBalance
2017-01-01 0
2017-01-09 78384.19
2017-01-13 600400.51
2017-01-18 749905.52
2017-01-20 152352.19
2017-02-16 154785.3
2017-02-17 365895.28
2017-02-20 284384.77
2017-02-28 284384.77
2017-03-06 829957.21
2017-03-07 1470165.4
2017-03-08 1534915.04
2017-03-20 1321371.95
2017-03-22 1525026.15
2017-04-13 1619142.93
2017-04-14 1947051.04
2017-04-19 2079602.99
2017-04-20 1330376.35
在这个数据框中,我想找到每日客户余额的平均值。现在我不能简单地使用 df['DailyCustomerBalance'].mean() #o/p 907116.755
它给了我错误的答案,因为没有很少的日期。我需要将缺勤日期视为以前的日期值(类似于ffill
(。
到目前为止,我已经尝试了以下脚本:
df['Pstng Date']=pd.to_datetime(df['Pstng Date'])
df['temp']=df['Pstng Date'].shift(-1)
df['maintained_days']=((df['temp'].sub(df['Pstng Date']))/np.timedelta64(1,'D')).fillna(1)
df['DailyCustomerBalanceWeightedWithDate']=(df['DailyCustomerBalance']*df['maintained_days'])
print (df['DailyCustomerBalanceWeightedWithDate'].sum())/(((df['Pstng Date'].max()-df['Pstng Date'].min())/np.timedelta64(1,'D'))+1)
output:
780359.246909 #ok
我上面的代码工作正常。但是我为这个问题使用了太多的操作。
还有其他更好的方法来解决这个问题吗?或任何其他数学方法简化这个问题?。
提前感谢,
您要确保日期在索引中。 使用pd.DataFrame.asfreq
和pd.DataFrame.mean
df.set_index('Pstng Date').asfreq('D').ffill().mean()
DailyCustomerBalance 780359.246909
dtype: float64