Home > Blockchain >  Replace value in DataFrame when value not empty
Replace value in DataFrame when value not empty

Time:10-21

I want to replace the values from a DataFrame column with values from a List.

How do I replace them only when the value in the list is not an empty string ?

Both are ordered the same way :

    Dataframe                  List

ID     Date                  UpdatedDate
1      19/04/2022            20/10/2022
2      12/07/2022                  
3      27/09/2022            03/10/2022
4      11/05/2022            14/10/2022
5      04/10/2022                  
6      02/08/2022            19/10/2022

I want this to become a single dataframe with the updated dates.

ID     Date
1      20/10/2022
2      12/07/2022                  
3      03/10/2022
4      14/10/2022
5      04/10/2022                  
6      19/10/2022

Any suggestions? Much appreciated.

CodePudding user response:

Assuming you list is a list that looks like this:

lst = ['20/10/2022', '', '03/10/2022', '14/10/2022', '', '19/10/2022']

You can add that to your df as a new column like this:

df['lst'] = lst

         Date         lst
0  19/04/2022  20/10/2022
1  12/07/2022            
2  27/09/2022  03/10/2022
3  11/05/2022  14/10/2022
4  04/10/2022            
5  02/08/2022  19/10/2022

you can then use .replace() on the lst column to replace the empty strings with np.nan (may need to add import numpy as np for this). Then use .fillna() to fill in the gaps in lst with Date:

df['Date'] = df['lst'].replace('', np.nan).fillna(df['Date'])

         Date         lst
0  20/10/2022  20/10/2022
1  12/07/2022            
2  03/10/2022  03/10/2022
3  14/10/2022  14/10/2022
4  04/10/2022            
5  19/10/2022  19/10/2022

Then drop the 'lst' column to get the final df:

df = df.drop('lst', axis=1)

         Date
0  20/10/2022
1  12/07/2022
2  03/10/2022
3  14/10/2022
4  04/10/2022
5  19/10/2022
  • Related