作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有几个 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_index
与 loc
:
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)
关于python - Pandas fillna : How to fill only leading NaN from beginning of series until first value appears?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051805/
我是一名优秀的程序员,十分优秀!