[英]How do I calculate the difference between a day and the corresponding day a week before in pandas?
[英]How do I calculate day on day difference in a pandas dataframe
我在數據庫中有一個自定義表,用於存儲每個工作日的每日余額。 我想在此表中添加一個名為 daily_difference 的新列。 這是應該如何計算的:
1.) 當一個賬戶第一次出現在這個表上時,每日差額應該是賬戶關閉時的余額。 2.) 如果賬戶之前已經記錄過,那么 daily_difference = 記錄日的期末余額 - 前一天的期末余額(請記住,即使一個賬戶的余額為 0,該賬戶仍然會有相應的close_balance 條目)。
請參閱下表以幫助您實現我的期望。
data = {
'Cust_Id': ['A', 'B', 'C', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'E'],
'Report_Date': ['01/12/2020', '01/12/2020', '01/12/2020', '02/12/2020', '02/12/2020', '02/12/2020', '02/12/2020',
'03/12/2020', '03/12/2020', '03/12/2020', '03/12/2020', '04/12/2020', '04/12/2020', '04/12/2020',
'04/12/2020', '04/12/2020'],
'Closing_Balance': [10000, 0, 5000, 2000, 16000, 10000, 1500, 5000, 12000, 7500, 0, 7000, 14000, 3000, 4000,
10000],
'Daily_Difference[Target Column]': [10000, 0, 5000, -8000, 16000, 5000, 1500, 3000, -4000, -2500, -1500, 2000,
2000, -4500, 4000, 10000]
}
df = pd.DataFrame(data)
如果您對我有任何問題,請告訴我。 太感謝了!
旁注:此數據集的大小將繼續增長。 我希望您在提供答案時考慮到這一點,因為計算速度非常重要。
將diff
與fillna
結合起來:
df.groupby(['Cust_Id'])['Closing_Balance'].diff().fillna(df['Closing_Balance'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.