20

I have a set of DataFrames with numeric values and partly overlapping indices. I would like to merge them an take the mean if an index occurs in more than one DataFrame.

import pandas as pd
import numpy as np

df1 = pd.DataFrame([1,2,3], columns=['col'], index=['a','b','c'])
df2 = pd.DataFrame([4,5,6], columns=['col'], index=['b','c','d'])

This gives me two DataFrames:

   col            col
a    1        b     4
b    2        c     5
c    3        d     6

Now I would like to merge the DataFrames and take the mean for each index (if applicable, i.e. if it occurs more than once).

Should look like this:

    col
a     1
b     3
c     4
d     6

Can I do this with some advanced merging/joining?

4

2 回答 2

19

像这样的东西:

df3 = pd.concat((df1, df2))
df3.groupby(df3.index).mean()

#    col
# a    1
# b    3
# c    4
# d    6

或其他方式,如@unutbu 回答:

pd.concat((df1, df2), axis=1).mean(axis=1)
于 2013-10-21T09:04:12.227 回答
5
In [22]: pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)
Out[23]: 
a    1
b    3
c    4
d    6
dtype: float64

关于 Roman 的问题,我发现IPython%timeit命令是一种对代码进行基准测试的便捷方法:

In [28]: %timeit df3 = pd.concat((df1, df2)); df3.groupby(df3.index).mean()
1000 loops, best of 3: 617 µs per loop

In [29]: %timeit pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)
1000 loops, best of 3: 577 µs per loop

In [39]: %timeit pd.concat((df1, df2), axis=1).mean(axis=1)
1000 loops, best of 3: 524 µs per loop

在这种情况下,pd.concat(...).mean(...)结果会更快一些。但实际上我们应该测试更大的数据帧以获得更有意义的基准。

顺便说一句,如果您不想安装 IPython,可以使用Python 的timeit模块运行等效的基准测试。它只需要更多的设置。该文档有一些示例显示如何执行此操作。


请注意,如果df1df2将在其索引中包含重复条目,例如:

N = 1000
df1 = pd.DataFrame([1,2,3]*N, columns=['col'], index=['a','b','c']*N)
df2 = pd.DataFrame([4,5,6]*N, columns=['col'], index=['b','c','d']*N)

那么这三个答案给出了不同的结果:

In [56]: df3 = pd.concat((df1, df2)); df3.groupby(df3.index).mean()
Out[56]: 
   col
a    1
b    3
c    4
d    6

pd.merge可能不会给出你想要的那种答案:

In [58]: len(pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1))
Out[58]: 2002000

虽然pd.concat((df1, df2), axis=1)引发了 ValueError:

In [48]: pd.concat((df1, df2), axis=1)
ValueError: cannot reindex from a duplicate axis
于 2013-10-21T09:05:27.217 回答