如何在 reduce over Pandas 合并函数中传递关键字参数

How to pass keyword arguments in reduce over Pandas merge function

我有以下数据框列表:

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', 'w']), ('Gene', ['foo', 'bar', 'wux']), ('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 [35]: tmp
Out[35]:
[  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     w  wux  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
3     w  wux    22.12      0    

我试过了但是没用

In [25]: reduce(pd.merge,how="outer",tmp)
  File "<ipython-input-25-1b2a5f2dd378>", line 1
    reduce(pd.merge,how="outer",tmp)
SyntaxError: non-keyword arg after keyword arg

正确的做法是什么?

+1 函数式编程风格。耶!

一种方法是使用 functools.partial 部分应用合并功能。

import functools
outer_merge = functools.partial(pd.merge, how="outer")
reduce(outer_merge, tmp)

第一次尝试得到:

In [25]: reduce(outer_merge, tmp)
Out[25]: 
  Probe Gene    RP1    RP2
0     x  foo   1.00  11.33
1     y  bar  23.22  31.25
2     z  qux  11.12    NaN
3     w  wux    NaN  22.12

[4 rows x 4 columns]

它揭示了你所说的关于你想要的结果的一些不一致之处。您可以看到实际上有两个位置外部合并必须提供缺失值,而不仅仅是一个。

作为最后一步,您可以使用 fillna 输入零值:

In [26]: reduce(outer_merge, tmp).fillna(0)
Out[26]: 
  Probe Gene    RP1    RP2
0     x  foo   1.00  11.33
1     y  bar  23.22  31.25
2     z  qux  11.12   0.00
3     w  wux   0.00  22.12

[4 rows x 4 columns]