0

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.

3
  • Is your list actually a list? or a series? Commented Oct 20, 2022 at 8:31
  • It is a list, with either a date or empty string Commented Oct 20, 2022 at 8:35
  • ah ok, let me update my answer Commented Oct 20, 2022 at 8:37

1 Answer 1

1

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

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.