我试图将pandas
中的两个数据帧合并到一个公共列名(orderid)上。结果数据帧(合并的数据帧)正在从第二个数据帧中删除orderid。根据{{3}},' on'除非您明确告知不要,否则应保留该列。
import pandas as pd
df = pd.DataFrame([[1,'a'], [2, 'b'], [3, 'c']], columns=['orderid', 'ordervalue'])
df['orderid'] = df['orderid'].astype(str)
df2 = pd.DataFrame([[1,200], [2, 300], [3, 400], [4,500]], columns=['orderid', 'ordervalue'])
df2['orderid'] = df2['orderid'].astype(str)
pd.merge(df, df2, on='orderid', how='outer', copy=True, suffixes=('_left', '_right'))
哪个输出:
| |orderid | ordervalue_left | ordervalue_right |
|------|--------|-----------------|------------------|
| 0 | 1 | a | 200 |
| 1 | 2 | b | 300 |
| 2 | 3 | c | 400 |
| 3 | 4 | | 500 |
我想要创建的是:
| | orderid_left | ordervalue_left | orderid_left | ordervalue_right |
|------|--------------|-----------------|--------------|------------------|
| 0 | 1 | a | 1 | 200 |
| 1 | 2 | b | 2 | 300 |
| 2 | 3 | c | 3 | 400 |
| 3 | NaN | NaN | 4 | 500 |
我该怎么写呢?
答案 0 :(得分:4)
重命名orderid
列,以便df
有一个名为orderid_left
的列,
df2
有一个名为orderid_right
的列:
import pandas as pd
df = pd.DataFrame([[1,'a'], [2, 'b'], [3, 'c']], columns=['orderid', 'ordervalue'])
df['orderid'] = df['orderid'].astype(str)
df2 = pd.DataFrame([[1,200], [2, 300], [3, 400], [4,500]], columns=['orderid', 'ordervalue'])
df2['orderid'] = df2['orderid'].astype(str)
df = df.rename(columns={'orderid':'orderid_left'})
df2 = df2.rename(columns={'orderid':'orderid_right'})
result = pd.merge(df, df2, left_on='orderid_left', right_on='orderid_right',
how='outer', suffixes=('_left', '_right'))
print(result)
产量
orderid_left ordervalue_left orderid_right ordervalue_right
0 1 a 1 200
1 2 b 2 300
2 3 c 3 400
3 NaN NaN 4 500