new = pd.DataFrame({'table': \['a','b', 'c', 'd'\], 'desc': \['','','',''\], 'total':\[22,22,22,22\]})
old = pd.DataFrame({'table': \['a','b', 'e'\], 'desc': \['foo','foo','foo'\], 'total':\[11,11,11\]})
all = pd.merge(new, old, how='outer', on=\['table', 'total'\])
輸出:
table desc_x total desc_y
0 a 22 NaN
1 b 22 NaN
2 c 22 NaN
3 d 22 NaN
4 a NaN 11 foo
期望的輸出:
table desc total
0 a foo 22
1 b foo 22
2 c 22
3 d 22
4 a foo 11
我嘗試外連接,但它洗掉了 a 和 b 的描述。
uj5u.com熱心網友回復:
- 考慮到您要實作的目標是在table和total上進行外部聯接,這毫無意義。更改為表上的外連接
- 然后可以修改表以使用所需的輸出和清理列中隱含的首選項
new = pd.DataFrame({'table': ['a','b', 'c', 'd'], 'desc': ['','','',''], 'total':[22,22,22,22]})
old = pd.DataFrame({'table': ['a','b', 'e'], 'desc': ['foo','foo','foo'], 'total':[11,11,11]})
all = pd.merge(new, old, how='outer', on=['table'])
# select prefered columns
all["desc"] = all["desc_x"].replace('', np.nan).fillna(all["desc_y"]).fillna("")
all["total"] = all["total_x"].fillna(all["total_y"])
# clean up columns
all = all.drop(columns=[c for c in all.columns if c[-2:] in ["_x", "_y"]])
all
| 桌子 | 描述 | 全部的 | |
|---|---|---|---|
| 0 | 一種 | 富 | 22 |
| 1 | b | 富 | 22 |
| 2 | C | 22 | |
| 3 | d | 22 | |
| 4 | e | 富 | 11 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/451338.html
上一篇:如何連接具有多個ID的資料框?
