Skip to content
Advertisement

Merging pandas columns into a new column

Suppose I have a dataframe as follows

     earningspersharebasic earningsPerShareBasic
2019                 -0.19                   NaN
2018                   NaN                  4.00
2017                   NaN                  0.21
2016                  0.01                   NaN

how can I merge the two columns into one using pandas? The desired output is

output

     earningspersharebasic
2019                 -0.19
2018                  4.00
2017                  0.21
2016                  0.01

Thank you!

Advertisement

Answer

Use Series.fillna with DataFrame.pop for replace missing values to another column with drop second column:

df['earningspersharebasic'] = df['earningspersharebasic'].fillna(df.pop('earningsPerShareBasic'))
print (df)
      earningspersharebasic
2019                  -0.19
2018                   4.00
2017                   0.21
2016                   0.01

Or you can back filling missing values with select first column by DataFrame.iloc with [[0]] for one column DataFrame from first column:

df = df.bfill(axis=1).iloc[:, [0]]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement