【发布时间】:2016-04-10 20:13:02
【问题描述】:
假设我有 3 个数据框,每个数据框都有一列。在每个 df 中,行数略多于前一个。例如: 我想得到这个:
df1 = col1
1 a
2 b
3 c
df2 = col2
1 x
2 y
3 z
4 w
5 q
df3 = col3
1 A
2 B
3 C
4 D
5 E
6 F
7 G
我想得到这个:
res = col1 col2 col3
1 a x A
2 b y B
3 c z C
4 - w D
5 - q E
6 - - F
7 - - G
也就是说,我希望行保持添加顺序,因此 NaN (-) 保留在底部。 我试过这个:
import pandas as pd
total = pd.DataFrame()
total = pd.merge(total,df1,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df2,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df3,how='outer',left_index=True,right_index=True)
但我一直以看似随机的顺序获取表格。像这样的东西:
res = col1 col2 col3
1 a x A
4 - w D
3 c z C
5 - q E
2 b y B
7 - - G
6 - - F
如何强制最终的 df 采用所需的形式? 谢谢!
【问题讨论】:
标签: python python-2.7 pandas merge dataframe