-2

I have a excel sheet like below.

enter image description here

I want to merge all those hierarichial columns into 1 column like below using pandas

enter image description here

Is there any way to merge like that if yes please tell me how?

Eswar RDS
  • 351
  • 1
  • 3
  • 11

1 Answers1

2

You can use df.bfill with axis = 1 then use iloc to extract first column

>>> import pandas as pd
>>> df = pd.DataFrame([[1, None, None, None], [None, 2, None, None], [None, None, 3, None], [None, None, None, 4]])
>>> df
     0    1    2    3
0  1.0  NaN  NaN  NaN
1  NaN  2.0  NaN  NaN
2  NaN  NaN  3.0  NaN
3  NaN  NaN  NaN  4.0
>>> df = df.bfill(axis=1).iloc[:, 0]
>>> df
0    1.0
1    2.0
2    3.0
3    4.0
Name: 0, dtype: float64
deadshot
  • 8,881
  • 4
  • 20
  • 39