Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python pandas stop fillna at last non NaN value

I have a dataframe where the index is date increasing and the columns are observations of variables. The array is sparse. My goal is to propogate forward in time a known value to fill NaN but I want to stop at the last non-NaN value as that last value signifies the "death" of the variable.

e.g. for the dataset

a b c
2020-01-01 NaN 11 NaN
2020-02-01 1 NaN NaN
2020-03-01 NaN NaN 14
2020-04-01 2 NaN NaN
2020-05-01 NaN NaN NaN
2020-06-01 NaN NaN 15
2020-07-01 3 NaN NaN
2020-08-01 NaN NaN NaN
question from:https://stackoverflow.com/questions/65886163/python-pandas-stop-fillna-at-last-non-nan-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use DataFrame.where for forward filling by mask - testing only non missing values by back filling them:

df = df.where(df.bfill().isna(), df.ffill())
print (df)
              a     b     c
2020-01-01  NaN  11.0   NaN
2020-02-01  1.0   NaN   NaN
2020-03-01  1.0   NaN  14.0
2020-04-01  2.0   NaN  14.0
2020-05-01  2.0   NaN  14.0
2020-06-01  2.0   NaN  15.0
2020-07-01  3.0   NaN   NaN
2020-08-01  NaN   NaN   NaN

Your solution should be used too if compare Series converted to numpy array with broadcasting:

mask = df.notna()[::-1].idxmax().to_numpy() < df.index.to_numpy()[:, None]
df = df.where(mask, df.ffill())
print (df)
              a     b     c
2020-01-01  NaN  11.0   NaN
2020-02-01  1.0   NaN   NaN
2020-03-01  1.0   NaN  14.0
2020-04-01  2.0   NaN  14.0
2020-05-01  2.0   NaN  14.0
2020-06-01  2.0   NaN  15.0
2020-07-01  3.0   NaN   NaN
2020-08-01  NaN   NaN   NaN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...