gpt4 book ai didi

python - Pandas fillna : How to fill only leading NaN from beginning of series until first value appears?

转载 作者:行者123 更新时间:2023-11-28 21:37:44 25 4
gpt4 key购买 nike

我有几个 pd.Series,它们通常以一些 NaN 值开头,直到出现第一个实际值。我想用 0 填充这些前导 NaN,但不想用 0 填充该系列后面出现的任何 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 和前向填充 NaNs:

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)

关于python - Pandas fillna : How to fill only leading NaN from beginning of series until first value appears?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com