2015-02-24 44 views
1

我与熊猫试验,并与合并所面临的问题,铁熊猫合并不同datato dataframes实现特定的输出

打印DF

        0       1   2 
0       plot_title     title1 title2 
1        x_title       x   x 
2        y_title      Speed   y 
3        x_val0      xv0  NaN 
4        x_val1      xv1  v1 
5        exp1     3159.6  3200 
6        exp2     2441.2  NaN 

打印df_to合并

  0  1 
0 plot_title title 
1  x_title  x 
2  y_title  ro 
3  x_val Nan 
4  exp1  19 
5  exp7 127 

和我想实现

        0  1   2  3 
0       plot_title title1 title2 title 
1        x_title  x   x  x 
2        y_title Speed   y  ro 
3        x_val0  xv0  NaN NaN 
4        x_val1  xv1  v1 NaN 
5        exp1 3159.6  3200  19 
6        exp2 2441.2  NaN Nan 
7        exp7  NaN  NaN 127 

我该怎么做?谢谢。

UPDATE: jeanrjc答案后,我得到一个关键的错误

File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3812) 
    File "pandas/index.pyx", line 156, in pandas.index.IndexEngine.get_loc (pandas/index.c:3749) 
KeyError: '0', 

,但如果我

DF2 = df.merge(df_to合并,如何= '外',left_on运行=“0”,right_on = 0)。我得到

上输出,DF2:

  0  1   0  1 
0 plot_title title1 plot_title title 
1  x_title  x  x_title  x 
2  y_title Speed  y_title  ro 
3  x_val0  xv0  x_val0 NaN 
4  x_val1  xv1  x_val1 NaN 
5  exp1 3159.6  exp1  19 
6  exp2 2441.2  exp2 NaN 
7  x_val  NaN  x_val Nan 
8  exp7  NaN  exp7 127 
+0

合并()将做到这一点。可能需要重新命名你的列中的2个后合并 – 2015-02-24 13:12:24

+0

你可以扩大你的答案吗? – alohamaloha 2015-02-24 13:17:29

回答

1

你需要做的与 “外” 模式合并:

df2 = df.merge(df_to merge, how='outer', left_on="0", right_on="0") 

和重命名列:

df2.columns = range(4) 

这给出:

  0  1  2  3 
0 plot_title title1 title2 title 
1  x_title  x  x  x 
2  y_title Speed  y  ro 
3  x_val0  xv0  NaN NaN 
4  x_val1  xv1  v1 NaN 
5  exp1 3159.6 3200  19 
6  exp2 2441.2  NaN NaN 
7  x_val  NaN  NaN Nan 
8  exp7  NaN  NaN 127 

请注意,来自df_to_merge的x_val不在您的预期输出中,我想这是一个错误,不是吗?

编辑:

要重新排序行:

df2 = df2.reindex(index=[1,2,3,4,7,5,6,8]) 
df2.index = range(1,9) 

这给:

  0  1  2 3 
1 x_title  x  x x 
2 y_title Speed  y ro 
3 x_val0  xv0 NaN NaN 
4 x_val1  xv1 v1 NaN 
5 x_val  NaN NaN Nan 
6  exp1 3159.6 3200 19 
7  exp2 2441.2 NaN NaN 
8  exp7  NaN NaN 127 

HTH

+0

不幸的是:pandas.index.IndexEngine.get_loc(pandas/index.c:3812)中的文件“pandas/index.pyx”,第134行,pandas.index中的文件“pandas/index.pyx”,第156行。 IndexEngine.get_loc(pandas/index.c:3749) KeyError:'0' – alohamaloha 2015-02-24 13:28:24

+0

您是否在'0'处引用了引号? – jrjc 2015-02-24 13:36:57

+0

@DmitryMarkovnikov,你有什么版本的熊猫? – jrjc 2015-02-24 14:31:36