熊猫-填充nans直到第一个非NULL值


9

我有一个数据框

A    B    C
1    nan  nan
2    nan  5
3    3    nan
4    nan  nan

我如何只填充每个系列的NULL(以0表示),直到第一个非NULL值,导致

A    B    C
1    0    0
2    0    5
3    3    nan
4    nan  nan

Answers:


6

pandas.DataFrame.ffillnotnaand一起使用的技巧where

df.where(df.ffill().notna(), 0)

或使用pandas.DataFrame.interpolate

df.interpolate('zero', fill_value=0, limit_direction='backward')

输出:

   A    B    C
0  1  0.0  0.0
1  2  0.0  5.0
2  3  3.0  NaN
3  4  NaN  NaN

6

这可以使用where或来完成mask

df.mask(df.notna().cumsum().eq(0), 0)
# or,
df.where(df.notna().cumsum().ne(0), 0)

   A    B    C
0  1  0.0  0.0
1  2  0.0  5.0
2  3  3.0  NaN
3  4  NaN  NaN

在这里给猫皮很多方法:-)


0

由于0 + nan是nan,因此可以工作:

xf = df.fillna(0) + df.bfill()*0
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.