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
310 views
in Technique[技术] by (71.8m points)

python - How to replace NaNs with some change in previous values in Pandas DataFrame?

    0    1     2
0   10   20   30
1   40   NaN  60
2   50   55   90
3   60   NaN  80
4   70   75   90

What I need to do is replace every NaN value with 30 , 65 respectively. That means ten added to previous value

question from:https://stackoverflow.com/questions/65650780/how-to-replace-nans-with-some-change-in-previous-values-in-pandas-dataframe

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

1 Reply

0 votes
by (71.8m points)

You can shift the dataframe and then add 10 , then fillna with that df:

df = df.fillna(df.shift().add(10))
# for a new df :-> new_df = df.fillna(df.shift().add(10))

print(new_df)

    0     1   2
0  10  20.0  30
1  40  30.0  60
2  50  55.0  90
3  60  65.0  80
4  70  75.0  90

Note: If you have both numeric and string columns, you can first select only numeric columns using df.select_dtypes and then do the operation:

num_df = df.select_dtypes(np.number)
df.loc[:,num_df.columns] = num_df.fillna(num_df.shift().add(10))

If you want to create a new df and not modify the original one then use df.assign to assign the new values to the subset of columns:

new_df = df.assign(**num_df.fillna(num_df.shift().add(10)))

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

...