首页 > 解决方案 > 如何替换DataFrame中的缺失数据

问题描述

假设我有以下数据框:

df = pd.DataFrame({'col1': [241, 123, 423], 'col2':[977, 78, np.NaN], 'col3':[76, 432, np.NaN], 'col4':[234, 321, 987]}, index=pd.date_range('2019-1-1', periods=3, freq="D")).rename_axis('Date')

输出:

            col1   col2   col3  col4
Date                                
2019-01-01   241  977.0   76.0   234
2019-01-02   123   78.0  432.0   321
2019-01-03   423    NaN    NaN   987

另一个数据框,甚至是一个系列,缺少col2和的值col3。如何NaN用来自的值替换这些值df2

df2 = pd.DataFrame({'col2': 111, 'col3': 222}, index=[pd.to_datetime('2019-1-3')]).rename_axis('Date')

看起来像:

            col2  col3
Date                  
2019-01-03   111   222

我想要的最终 DataFrame 应该是这样的:

            col1   col2   col3  col4
Date                                
2019-01-01   241  977.0   76.0   234
2019-01-02   123   78.0  432.0   321
2019-01-03   423    111    222   987

标签: pythonpandasdataframe

解决方案


我们可以使用DataFrame.fillna

df=df.fillna(df2)
print(df)

            col1   col2   col3  col4
Date                                
2019-01-01   241  977.0   76.0   234
2019-01-02   123   78.0  432.0   321
2019-01-03   423  111.0  222.0   987

如果你有一个按列排列的系列,就像用我们获得的那样,df2.iloc[0]我们也可以这样做:

my_serie=df2.iloc[0]
print(my_serie)
col2    111
col3    222
Name: 2019-01-03 00:00:00, dtype: int64

print(df.fillna(my_serie))
            col1   col2   col3  col4
Date                                
2019-01-01   241  977.0   76.0   234
2019-01-02   123   78.0  432.0   321
2019-01-03   423  111.0  222.0   987

推荐阅读