Skip to main content
 首页 » 编程设计

python之pandas系列如何用最后一个有效值填充na

2025年05月04日12duanxz

我有一个 Pandas 系列,我想填充最后一个不是 nan 的值。例如,

a=pd.Series({1: 1918,  2: 1928, 3: np.nan, 4: np.nan, 5: np.nan, 6: 1853, 7: 1831}) 
Out[113]:  
1    1918 
2    1928 
3     NaN 
4     NaN 
5     NaN 
6    1853 
7    1831 
dtype: float64 

我想要的是:

a=pd.Series({1: 1918, 
2: 1928, 
3: np.nan, 
4: np.nan, 
5: 1928, 
6: 1853, 
7: 1831}) 

有没有一种优雅的方式来做到这一点?我试着查看 fillna,但它没有我要找的这个选项。它将用 1928 填充值 3 或用 1853 填充值 5(使用 limit=1),但这不是我要找的。最终目标是根据这些数据做一个返回系列,当值为 nan 时,使用最后一个不是 nan 的可用数据。因此,新的返回系列应该给出 spot 6, 1853/1928 -1 。

请您参考如下方法:

您可以通过 isnull 创建掩码和 shift然后使用 loc和 fillna :

import pandas as pd 
import numpy as np 
 
a=pd.Series({1: 1918,  2: 1928, 3: np.nan, 4: np.nan, 5: np.nan, 6: 1853, 7: 1831}) 
print a 
1    1918 
2    1928 
3     NaN 
4     NaN 
5     NaN 
6    1853 
7    1831 
dtype: float64 
 
print ~(pd.isnull(a) & pd.isnull(a.shift(-1))) 
1     True 
2     True 
3    False 
4    False 
5     True 
6     True 
7     True 
dtype: bool 
 
a.loc[ ~(pd.isnull(a) & pd.isnull(a.shift(-1)))] = a.fillna(method='ffill') 
print a 
1    1918 
2    1928 
3     NaN 
4     NaN 
5    1928 
6    1853 
7    1831 
dtype: float64