Home > Blockchain >  Replace nan value dynamically in pandas
Replace nan value dynamically in pandas

Time:11-24

I'm trying to replace NaN values in the below pandas df column with two separate values i.e 8 and 12.


  |  ColumnD   |
   ------------ 
  |    6       |
  |    NaN     |
  |    10      |
  |    NaN     |
  |    14      |

I'm currently able to achieve this manually using iloc of the data frame like below :

df.iloc[1:2, 0] = 8
df.iloc[3:4, 0] = 12

Is there a way, wherein I can replace the NaN values (with 8 and 12) by adding 2 to the previous value of Nan's and not directly replacing the NaN with 8 and 12 ?

CodePudding user response:

Use np.where to conditionally fillna

df['ColumnD']=np.where(df['ColumnD'].isna(),df['ColumnD'].fillna(method='ffill') 2, df['ColumnD'])

    ColumnD
0      6.0
1      8.0
2     10.0
3     12.0
4     14.0
  • Related