Skip to main content
 首页 » 编程设计

python之也使用 NA 值的 Series.update()

2024年10月25日13zhoujg

some_series.update(other_series) 将用 other_series 中的匹配(按索引)值覆盖 some_series 上的所有值。但是,它确实会跳过所有 NA 值,例如 None。

如果我想从 other_series 更新 some_series,但还要应用 NA 值,我应该使用什么?

澄清一下,这就是我想要的:

In [197]: some_series 
Out[197]:  
0    1 
1    2 
dtype: int64 
 
In [198]: other_series 
Out[198]:  
0    None 
dtype: object 
 
In [203]: some_series  # after overriding it with other_series: 
Out[203]:  
0    None 
1       2 
dtype: object 

请您参考如下方法:

以下是可行的,它使用 loc 和其他系列索引来屏蔽我们要覆盖的元素:

In [106]: 
 
some_series = pd.Series([1, 2]) 
other_series = pd.Series([None]) 
some_series.loc[other_series.index] = other_series 
some_series 
Out[106]: 
0   NaN 
1     2 
dtype: float64 

loc 在这种情况下是完全不必要的