Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I merge columns that have similar names in a pandas dataframe?

I have a dataframe which has the words Due Date written differently but it all means the same. The problem is in my master data(xls file), one due date has an extra space or doesnt and i cant change that.All i can change is my final output.

Sr no Due Date    Due Date   DueDate
1     1/2/22      
2                  1/5/22    
3
4                         
5                             ASAP

I just want that column 2 and 3 all combine under column one at the same location they were

Sr No.  Due Date
1        1/2/22
2        1/5/22
3        
4
5        ASAP

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use filter with a regex to get similar names, then bfill and get the first. Finally join to original devoid of the found columns:

d = df.filter(regex=r'(?i)due\s*date')
df2 = (df
 .drop(columns=list(d.columns))
 .join(d.bfill(1).iloc[:,0])
 )

Output:

   Sr no Due Date
0      1   1/2/22
1      2   1/5/22
2      3     None
3      4     None
4      5     ASAP
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading