Home > Net >  Joining columns in pandas with specific condition
Joining columns in pandas with specific condition

Time:03-22

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.

  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

CodePudding user response:

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
  • Related