Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reformat/pivot pandas dataframe

For each row, I want that rows’ index to be changed to column_index, and have the whole thing split from x row * y columns to 1 row * x*y columns shape.

import pandas as pd

df = pd.DataFrame(data=[['Jon', 21, 1.77,160],['Jane',44,1.6,130]],columns=['name','age', 'height','weight'])
want = pd.DataFrame(data=[['Jon', 21, 1.77,160,'Jane',44,1.6,130]],columns=['name_0','age_0', 'height_0','weight_0','name_1','age_1', 'height_1','weight_1'])

# original df
   name  age  height  weight
0   Jon   21    1.77     160
1  Jane   44    1.60     130

# desired df - want
  name_0  age_0  height_0  weight_0 name_1  age_1  height_1  weight_1
0    Jon     21      1.77       160   Jane     44       1.6       130

I tried df.unstack().to_frame().T and while it reduces the rows to one, it creates a multiindex, so not ideal:

  name       age     height      weight     
     0     1   0   1      0    1      0    1
0  Jon  Jane  21  44   1.77  1.6    160  130

I don’t think pivot table will work here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using stack and flattening the MultiIndex:

out = df.stack().swaplevel().to_frame().T
out.columns = out.columns.map(lambda x: f'{x[0]}_{x[1]}')

Output:

  name_0 age_0 height_0 weight_0 name_1 age_1 height_1 weight_1
0    Jon    21     1.77      160   Jane    44      1.6      130
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading