按预定义列连接/合并数据帧列表

时间:2015-02-03 06:08:06

标签: python pandas

我有以下数据框列表:

import pandas as pd
rep1 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP1',[1.00,23.22,11.12])], orient='columns')
rep2 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP2',[11.33,31.25,22.12])], orient='columns')
rep3 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux'])], orient='columns')
tmp = []
tmp.append(rep1)
tmp.append(rep2)
tmp.append(rep3)

# In actuality the DF could be more than 3.

产生:

In [53]: tmp
Out[53]:
[  Probe Gene    RP1
 0     x  foo   1.00
 1     y  bar  23.22
 2     z  qux  11.12,   Probe Gene    RP2
 0     x  foo  11.33
 1     y  bar  31.25
 2     z  qux  22.12,   Probe Gene
 0     x  foo
 1     y  bar
 2     z  qux]

我想要做的是连接数据帧列表,以便产生这样的结果:

  Probe Gene      RP1        RP2
0     x  foo     1.00      11.33
1     y  bar    23.22      31.25
2     z  qux    11.12      22.12

请注意,rep3只包含两列。在连接过程中,我们希望自动丢弃它。

我尝试使用此代码但无济于事。什么是正确的方法?

In [57]: full_df = pd.concat(tmp,axis=1).fillna(0)

In [58]: full_df
Out[58]:
  Probe Gene    RP1 Probe Gene    RP2 Probe Gene
0     x  foo   1.00     x  foo  11.33     x  foo
1     y  bar  23.22     y  bar  31.25     y  bar
2     z  qux  11.12     z  qux  22.12     z  qux

1 个答案:

答案 0 :(得分:1)

我不确定这是正确的方式,但一种巧妙的方法是使用reduce

In [11]: reduce(pd.merge, tmp)
Out[11]:
  Probe Gene    RP1    RP2
0     x  foo   1.00  11.33
1     y  bar  23.22  31.25
2     z  qux  11.12  22.12

这基本上相当于:

tmp[0].merge(tmp[1]).merge(tmp[2])...

注意:这意味着如果你在tmp中有很多DataFrame,它可能没有使用concat那么高效。