Skip to main content
 首页 » 编程设计

python之如何替换 DataFrame 中丢失的数据

2025年05月04日15cyq1162

假设我有以下 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 

另一个 Dataframe,甚至是一个 Series,缺少 col2 和 col3 的值。如何用 df2 中的值替换 NaN 值?

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 

请您参考如下方法:

我们可以使用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