忽略NaN值的两个数据帧的逐元素最大值

17

我有两个数据框(df1和df2),它们每个都有相同的行和列。我希望逐元素地取这两个数据框的最大值。此外,任何元素与数字和NaN之间的按元素最大值的结果应该是数字。到目前为止,我实现的方法似乎效率低下:

def element_max(df1,df2):
    import pandas as pd
    cond = df1 >= df2
    res = pd.DataFrame(index=df1.index, columns=df1.columns)
    res[(df1==df1)&(df2==df2)&(cond)]  = df1[(df1==df1)&(df2==df2)&(cond)]
    res[(df1==df1)&(df2==df2)&(~cond)] = df2[(df1==df1)&(df2==df2)&(~cond)]
    res[(df1==df1)&(df2!=df2)&(~cond)] = df1[(df1==df1)&(df2!=df2)]
    res[(df1!=df1)&(df2==df2)&(~cond)] = df2[(df1!=df1)&(df2==df2)]
    return res

还有其他的想法吗?感谢您的时间。

2个回答

22
在最近版本的pandas中,更易读的方法是使用concat-and-max:
import scipy as sp
import pandas as pd

A = pd.DataFrame([[1., 2., 3.]])
B = pd.DataFrame([[3., sp.nan, 1.]])

pd.concat([A, B]).max(level=0)
# 
#           0    1    2
#      0  3.0  2.0  3.0 
#

21
您可以使用where将df与另一个df进行比较,其中条件为True时,返回df的值;当条件为False时,返回df1的值。此外,在df1中存在NaN值的情况下,通过调用fillna(df)会使用df中的值来填充这些NaN,并返回所需的df:
In [178]:
df = pd.DataFrame(np.random.randn(5,3))
df.iloc[1,2] = np.NaN
print(df)
df1 = pd.DataFrame(np.random.randn(5,3))
df1.iloc[0,0] = np.NaN
print(df1)

          0         1         2
0  2.671118  1.412880  1.666041
1 -0.281660  1.187589       NaN
2 -0.067425  0.850808  1.461418
3 -0.447670  0.307405  1.038676
4 -0.130232 -0.171420  1.192321
          0         1         2
0       NaN -0.244273 -1.963712
1 -0.043011 -1.588891  0.784695
2  1.094911  0.894044 -0.320710
3 -1.537153  0.558547 -0.317115
4 -1.713988 -0.736463 -1.030797

In [179]:
df.where(df > df1, df1).fillna(df)

Out[179]:
          0         1         2
0  2.671118  1.412880  1.666041
1 -0.043011  1.187589  0.784695
2  1.094911  0.894044  1.461418
3 -0.447670  0.558547  1.038676
4 -0.130232 -0.171420  1.192321

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接