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

Joining columns in pandas with specific condition

My DataFrame looks like below:

Main_column column_1 column_2 column_3 column_4
qw          qw       NaN      rt       NaN
we          qe       NaN      qe       NaN
er          NaN      NaN      NaN      NaN
NaN         NaN      cg       NaN      NaN
NaN         NaN      NaN      vb       bn

DF should looks like below:

Main_column column_1 column_2 column_3 column_4 new_column
qw          qw       NaN      rt       NaN      qw
we          qe       NaN      qe       NaN      we
er          NaN      NaN      NaN      NaN      er
NaN         NaN      cg       NaN      NaN      cg
NaN         NaN      NaN      vb       bn       vb

So basically I need to create a new column based on values from privies one. There are 2 things that needs to be take into account.

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

  1. If there is a value in "Main_column", the same values should be in "new_column".
  2. If there is no values in "Main_column", we should take value from the next column (if there is any).

Do you have any idea how to do that?

Regards

>Solution :

Use –

df['new_column'] = df['Main_column'].copy()
for col in df.columns: 
    df['new_column'] = df['new_column'].fillna(df[col])

Output

0    qw
1    we
2    er
3    cg
4    vb
Name: Main_column, dtype: object
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