0
    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

0

2 Answers 2

4

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)))
Sign up to request clarification or add additional context in comments.

2 Comments

ThnakYou @anky . Your answer helped me.. first code gave me an error." can concatenate only str(not int) to str. Then i tried your your second code. it worked
@ElezabethJose That is because the second solution used only numerical columns.Glad I could help. If my answer helped solving your question, please consider accepting my answer by clicking on the grey tick mark to the left of the answer to make it green tick, so as to close the question.
3

You can try this as well:

df = df.fillna(df.fillna(method='ffill').add(10))

I find this method easier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.