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

2024-06-06 19:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧列表:

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)

使用此列表输出:

^{pr2}$

注意以下几点:

  • 每个DF将包含3列,但最后一列可以有不同的名称
  • rep3第3列没有值,我们想自动放弃它
  • w wux只存在于rep2中,我们希望包含该行并为不包含该行的其他数据帧提供值0。在

我要做的是执行外部合并,以便它产生以下结果:

  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

正确的方法是什么?在


Tags: columnsfromdataframefoobaritemstmpprobe
1条回答
网友
1楼 · 发布于 2024-06-06 19:18:28

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

一种方法是使用functools.partial部分应用merge函数。在

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

在第一次尝试时,这将给出:

^{pr2}$

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

最后一步,您可以使用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]

相关问题 更多 >