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

create column by looking not null values in other columns

I am trying to create a column in my dataframe which searches each column and checks if the value of at specific row is null or not, if it is not the new column will contain this value, otherwise it will skip it. It is not possible that two columns contains a non null value.

For example:

  A   B   C   D   E
NaN NaN NaN NaN   a 
  b NaN NaN NaN NaN
NaN NaN NaN NaN NaN 

My expected output:

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

  A   B   C   D   E  new_column
NaN NaN NaN NaN   a           a
  b NaN NaN NaN NaN           b
NaN NaN NaN NaN NaN         NaN

>Solution :

You can bfill horizontally and then select the first column:

df['new_column'] = df.bfill(axis=1).iloc[:, 0]

Output:

>>> df
     A   B   C   D    E new_column
0  NaN NaN NaN NaN    a          a
1    b NaN NaN NaN  NaN          b
2  NaN NaN NaN NaN  NaN        NaN
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