Home > Software design >  Replace all NaN value using the the value of another table
Replace all NaN value using the the value of another table

Time:09-08

How can I change null value and replace them using the value in the same row?

   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          NaN

I want to change NaN in index 2, replacing it with the value of user in index 2 and add 1 to it.

So that the NaN will become 2.0:

   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0

CodePudding user response:

Looks like you want fillna:

df['days_unseen'] = df['days_unseen'].fillna(df['user'].add(1))

Or, with boolean indexing:

df.loc[df['days_unseen'].isna(), 'days_unseen'] = df['user'].add(1)

output:

   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0

CodePudding user response:

I would suggest the following code:

import numpy as np
import pandas as pd
df = pd.DataFrame({'user': [1.0, 4.0, 1.0],'days_unseen': [2.0, 5.0, np.NaN]})
df.loc[df['days_unseen'].isna(), 'days_unseen'] = df.loc[df['days_unseen'].isna(), 'user']   1.0

CodePudding user response:

you were very close to a solution. Here is mine:

import pandas as pd


df = pd.read_csv('sample.csv')
print(f"Initial df:\n{df}")
df["days_unseen"] = df["days_unseen"].fillna(df["user"]   1)
print(f"\nFinal df:\n{df}")

Output:

Initial df:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          NaN

Final df:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0
  • Related