将pandas中的数据帧与相同的行和列组合,但不同的单元格值

时间:2016-10-05 21:04:53

标签: python pandas dataframe merge concat

我有兴趣在pandas中组合两个数据帧,这两个数据帧具有相同的行索引和列名,但具有不同的单元格值。请参阅以下示例:

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN],
                    'B':[23,4,np.NaN,np.NaN],
                    'C':[24,6,np.NaN,np.NaN],
                    'D':[25,8,np.NaN,np.NaN]})

df2 = pd.DataFrame({'A':[np.NaN,np.NaN,56,100],
                    'B':[np.NaN,np.NaN,58,101],
                    'C':[np.NaN,np.NaN,59,102],
                    'D':[np.NaN,np.NaN,60,103]})

In[6]: print(df1)
      A     B     C     D
0  22.0  23.0  24.0  25.0
1   2.0   4.0   6.0   8.0
2   NaN   NaN   NaN   NaN
3   NaN   NaN   NaN   NaN

In[7]: print(df2)
       A      B      C      D
0    NaN    NaN    NaN    NaN
1    NaN    NaN    NaN    NaN
2   56.0   58.0   59.0   60.0
3  100.0  101.0  102.0  103.0

我希望生成的框架看起来像这样:

       A      B      C      D
0   22.0   23.0   24.0   25.0
1    2.0    4.0    6.0    8.0
2   56.0   58.0   59.0   60.0
3  100.0  101.0  102.0  103.0

我尝试了不同的pd.concat和pd.merge方法,但有些数据总是被NaN取代。任何指向正确方向的人都会非常感激。

2 个答案:

答案 0 :(得分:2)

使用combine_first

print (df1.combine_first(df2))
       A      B      C      D
0   22.0   23.0   24.0   25.0
1    2.0    4.0    6.0    8.0
2   56.0   58.0   59.0   60.0
3  100.0  101.0  102.0  103.0

fillna

print (df1.fillna(df2))
       A      B      C      D
0   22.0   23.0   24.0   25.0
1    2.0    4.0    6.0    8.0
2   56.0   58.0   59.0   60.0
3  100.0  101.0  102.0  103.0

update

df1.update(df2)
print (df1)
       A      B      C      D
0   22.0   23.0   24.0   25.0
1    2.0    4.0    6.0    8.0
2   56.0   58.0   59.0   60.0
3  100.0  101.0  102.0  103.0

答案 1 :(得分:1)

使用combine_first

df1.combine_first(df2)