僅當 Account 位于 Account2 中時,我才嘗試使用 Pandas 添加列 Amount 和 Amount2。
輸入
Account Amount Account2 Amount2
0 0001957331 409.50 0404618555 26.31
1 0404618555 1535.40 0490812351 5.31
2 0490812351 338.12 0521656066 787.94
3 0696978386 13.11 0696978386 700.55
預期輸出:
0001957331 409.50
0404618555 1561.71
0490812351 343.43
0696978386 713.66
我的代碼:
df = pd.DataFrame(allc_acct_amt, columns=["Account", "Amount", "Account2", "Amount2"])
print(df)
dff = df.groupby(["Account","Account2"])[['Amount', 'Amount2']].sum().reset_index()
print(dff)
uj5u.com熱心網友回復:
使用merge:
out = pd.merge(df[['Account', 'Amount']], df[['Account2', 'Amount2']],
left_on='Account', right_on='Account2', how='left')
out = out.assign(Amount=out[['Amount', 'Amount2']].sum(1)) \
.drop(columns={'Account2', 'Amount2'})
輸出:
>>> out
Account Amount
0 0001957331 409.50
1 0404618555 1561.71
2 0490812351 343.43
3 0696978386 713.66
設定可重現:
data = {'Account': ['0001957331', '0404618555', '0490812351', '0696978386'],
'Amount': [409.5, 1535.4, 338.12, 13.11],
'Account2': ['0404618555', '0490812351', '0521656066', '0696978386'],
'Amount2': [26.31, 5.31, 787.94, 700.55]}
df = pd.DataFrame(data)
uj5u.com熱心網友回復:
mask = df["Account"] == df["Account2"]
df["total_amount"] = df["Amount"] df["Amount2"][mask]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388054.html
標籤:Python
上一篇:使用來自二維numpy陣列的單個向量列創建PandasDataFrame
下一篇:即使在添加中斷后輸出也會多次列印
