简体   繁体   中英

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:

  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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM