finmathstudent
finmathstudent

Reputation: 189

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!

Upvotes: 1

Views: 50

Answers (2)

Suman Dey
Suman Dey

Reputation: 151

enter image description here

Filled the missing values with 0 and took the sum total of both the columns. You can also opt for the solution provided by @jezrael.

Upvotes: 0

jezrael
jezrael

Reputation: 862511

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]]

Upvotes: 2

Related Questions