預先感謝您的幫助。
我對 Python 完全陌生,我嘗試了不同的方法來實作所需的東西(主要是使用groupby()
),但到目前為止一切都失敗了。
我有一個資料框,其中包含同一天不同貨幣的多項交易(116200 行):
指數 | 戶口號碼 | 提款AMT | 存入 AMT | 日期 | 貨幣 |
---|---|---|---|---|---|
0 | 12345567 | 100 | 300 | 2015-01-01 | 歐元 |
1 | 12345567 | 100 | 300 | 2015-01-01 | 美元 |
2 | 12345567 | 100 | 300 | 2015-01-01 | 英鎊 |
3 | 12345567 | 100 | 300 | 2015-01-01 | 歐元 |
4 | 34334123 | 100 | 300 | 2015-01-02 | 美元 |
5 | 34334123 | 100 | 300 | 2015-01-02 | 英鎊 |
我有兩個單獨的資料框,其中包含每天的匯率(一個是歐元兌英鎊,一個是美元兌英鎊):
指數 | 歐元-英鎊 | 日期 |
---|---|---|
0 | 1.634 | 2015-01-01 |
1 | 1.6676 | 2015-01-02 |
2 | 1.4554 | 2015-01-03 |
3 | 1.23455 | 2015-01-04 |
指數 | 美元兌英鎊 | 日期 |
---|---|---|
0 | 0.934 | 2015-01-01 |
1 | 0.943 | 2015-01-02 |
2 | 0.834 | 2015-01-03 |
3 | 0.945 | 2015-01-04 |
首先,我需要想辦法將資料幀的第一個值轉換為 GBP。正如您所注意到的,每天都包括以不同貨幣進行的交易,因此任何有關如何做到這一點的提示都將不勝感激!
然后,我想在同一天創建一個每行只有一天的資料框,即將每一行與相應的提款和存款列的每日總和合并:
指數 | 提款AMT | 存入 AMT | 日期 | 貨幣 |
---|---|---|---|---|
0 | 1000 | 600 | 2015-01-01 | 英鎊 |
1 | 3000 | 500 | 2015-01-02 | 英鎊 |
2 | 2000年 | 700 | 2015-01-03 | 英鎊 |
再次感謝您花時間閱讀我的帖子!
PS 所有數字都是隨機的!
uj5u.com熱心網友回復:
你可以這樣做:
(假設您的主資料框名為df1
,則匯率資料框為df_xr_eur
和df_xr_usd
):
# Split the main dataframe by currency
df1_eur = df1[df1['Currency'] == 'eur'].copy()
df1_usd = df1[df1['Currency'] == 'usd'].copy()
df1_gbp = df1[df1['Currency'] == 'gbp'].copy()
# Calculate GBP equivalent of currency values
df1_eur['Withdrawal AMT'] *= df1_eur['Dates'].map(df_xr_eur.set_index('Dates')['EURO-GBP'])
df1_eur['Deposit AMT'] *= df1_eur['Dates'].map(df_xr_eur.set_index('Dates')['EURO-GBP'])
df1_usd['Withdrawal AMT'] *= df1_usd['Dates'].map(df_xr_usd.set_index('Dates')['USD-GBP'])
df1_usd['Deposit AMT'] *= df1_usd['Dates'].map(df_xr_usd.set_index('Dates')['USD-GBP'])
# Assemble the previously split datrframes after exchange rate calculation
df2 = pd.concat([df1_eur, df1_usd, df1_gbp]).assign(Currency='GBP')
# Aggregate by `Dates`
df_final = df2.groupby('Dates').agg({'Withdrawal AMT': 'sum',
'Deposit AMT': 'sum',
'Currency': 'first'
}).reset_index()
結果:
print(df_final)
Dates Withdrawal AMT Deposit AMT Currency
0 2015-01-01 520.2 1560.6 GBP
1 2015-01-02 194.3 582.9 GBP
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327965.html