pandas fillna:如何从系列开始到出现第一个值仅填充前导 NaN



我有几个pd.Series通常以一些 NaN 值开头,直到出现第一个实际值。我想用 0 填充这些领先的 NaN,但不填充本系列后面出现的任何 NaN。

pd.Series([nan, nan, 4, 5, nan, 7])

应该成为

ps.Series([0, 0, 4, 5, nan, 7])

first_valid_indexloc一起使用:

s.loc[:s.first_valid_index()] = 0

或者mask isnull和前向填充NaN s:

s = s.mask(s.ffill().isnull(), 0)
<小时 />
print (s)
0    0.0
1    0.0
2    4.0
3    5.0
4    NaN
5    7.0
dtype: float64

编辑:对于每个组的功能,请使用:

def func(x):
    x['col1'] = x['col1'].mask(x['col1'].ffill().isnull(), 0)
    return x

df = df.groupby('col').apply(func)

最新更新