通过循环合并Pandas DataFrame

时间:2015-01-07 05:34:35

标签: python pandas

我有3个数据框,如下所示:

In [1]: import pandas as pd 
In [26]: d1 = {'foo':0.3, 'bar':0.55} 
In [27]: d2 = {'foo':0.4, 'bar':0.55, 'qux':0.3}
In [28]: d3 = {'foo':0.1, 'qux':5.55}
In [29]: df1 = pd.DataFrame.from_dict(d1, orient='index')
In [31]: df2 = pd.DataFrame.from_dict(d2, orient='index')
In [32]: df3 = pd.DataFrame.from_dict(d3, orient='index')
In [43]: df1.columns = ['x']
In [45]: df2.columns = ['y']
In [46]: df3.columns = ['z']

In [50]: df1
Out[50]: 
        x
foo  0.30
bar  0.55

In [51]: df2
Out[51]: 
        y
qux  0.30
foo  0.30
bar  0.55

In [52]: df3
Out[52]: 
        z
qux  5.55
foo  0.30

我想要做的是合并它们并创建一个如下所示的单个大数据框:

      x      y     z
foo   0.3    0.4   0.1
qux   NA     0.3   5.55
bar   0.55   0.55  NA

我怎样才能做到这一点?

我尝试了但失败了:

dfs = [df1,df2,df3]
df = pd.DataFrame()
for d in dfs:
    df = pd.merge(df, d, how = 'outer')

1 个答案:

答案 0 :(得分:1)

>>> pandas.concat([df1, df2, df3], axis=1)
       x     y     z
bar  0.55  0.55   NaN
foo  0.30  0.40  0.10
qux   NaN  0.30  5.55