我正在嘗試從更大的 DataFrame 創建合并報告。我在將 MultiIndex 系列映射回 DataFrame 時遇到問題。我可以讓它適用于單索引系列。我想明確地使用兩列作為 groupby 的標準,并使用這兩列將系列映射回資料幀,以便我知道它被正確映射,以防單個 DealNum 有多個 FlowDates 用于興趣和溢價 FlowTypes .
關于如何正確完成此操作以及這是否是解決此問題的最佳方法的任何建議?我已經嘗試過 pivot_table 但在較大的資料集中有一些情況下它不能很好地作業。
謝謝。
完整代碼如下,我遇到問題的具體行是:
report['Interest-FlowDate-Daily_PnL'] = report[['DealNum','FlowDate']].map(interest_flowdate_series)
import pandas as pd
data = {
'DealNum': [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6],
'FlowType': ['Interest', 'Premium', 'Fees',
'Interest', 'Premium', 'Fees',
'Interest', 'Premium', 'Fees',
'Interest', 'Premium', 'Fees',
'Interest', 'Premium', 'Fees',
'Interest', 'Premium', 'Fees'],
'FlowDate': ['12/31/2021', '12/31/2021', '1/10/2021',
'11/30/2021', '11/30/2021', '2/8/2021',
'1/31/2022', '1/31/2022', '5/10/2021',
'2/28/2022', '2/28/2022', '7/28/2021',
'12/15/2021', '12/15/2021', '12/15/2021',
'6/30/2022', '6/30/2022', '11/10/2021',],
'Daily_PnL': [10,0,-2.25,
30,0,-1.50,
100,0,-3.50,
200,0,-2.50,
300,0,-4.50,
0,-150,-1.50,],
'LTD_PnL': [1000,-150,-102.25,
3000,0,-101.50,
1400,0,-103.50,
2400,0,-102.50,
4000,0,-104.50,
0,-150,-1.50,]
}
df = pd.DataFrame(data)
# Create Base Report using only FlowDates from Interest and Premium FlowTypes
report = df[(df.FlowType == 'Interest') | (df.FlowType == 'Premium')][['DealNum','FlowDate']].drop_duplicates().reset_index(drop=True)
#Create Interest Series to add back to Base Report using DealNum & FlowDate as criteria
interest_flowdate_series = df[df.FlowType == 'Interest'].groupby(['DealNum','FlowDate']).sum()['Daily_PnL']
report['Interest-FlowDate-Daily_PnL'] = report[['DealNum','FlowDate']].map(interest_flowdate_series)
print(interest_flowdate_series)
print(report)
uj5u.com熱心網友回復:
我不知道您的具體目標是什么,但它看起來像你使用map的方式來merge/ join。為什么不這樣做?
report.set_index(['DealNum','FlowDate']).join(interest_flowdate_series).reset_index()
或者:
report.merge(interest_flowdate_series, left_on=['DealNum','FlowDate'], right_index=True)
輸出:
DealNum FlowDate Fees-Daily_PnL Interest-Daily_PnL Daily_PnL
0 1 12/31/2021 -2.25 10.0 10.0
1 2 11/30/2021 -1.50 30.0 30.0
2 3 1/31/2022 -3.50 100.0 100.0
3 4 2/28/2022 -2.50 200.0 200.0
4 5 12/15/2021 -4.50 300.0 300.0
5 6 6/30/2022 -1.50 0.0 0.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/344539.html
