Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten DataFrame into a single row

I want to reorganize the following mutli-row DataFrame,

       1          2       3
A  Apple     Orange   Grape
B    Car      Truck   Plane
C  House  Apartment  Garage

into this, single-row DataFrame.

     1_A     2_A    3_A  1_B    2_B    3_B    1_C        2_C     3_C
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage

Thank you for your help!

like image 950
michael0196 Avatar asked Dec 24 '22 07:12

michael0196


1 Answers

unstack + sort_index to the rescue:

v = df.unstack().to_frame().sort_index(level=1).T
v.columns = v.columns.map('_'.join)

v
     1_A     2_A    3_A  1_B    2_B    3_B    1_C        2_C     3_C
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage
like image 117
cs95 Avatar answered Feb 16 '23 05:02

cs95