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

Pandas convert mutil-row-column dataframe to single-row multi-column dataframe

My dataframe is given below:

code:

df = 

Car measurements                Before      After
amb_temp                        30.268212  26.627491
engine_temp                     41.812730  39.254255
engine_eff                      15.963645  16.607557
avg_mile                        0.700160   0.733307
cor_mile                        0.761483   0.787538

Expected output:

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

modified_df = 
index amb_temp_Before  amb_temp_after      engine_temp_Before  engine_temp_after ...
0      30.268212            26.627491          41.812730          39.254255  ...

                 
                  

Present output:

print(df.pivot(columns='index',value=['Before','After']))
    amb_temp   engine_temp                      amb_temp 
0   30.268212   NaN     NaN     NaN     NaN     26.627491   NaN     NaN     NaN     NaN
1   NaN     NaN     NaN     41.81273    NaN     NaN     NaN     NaN     39.254255   NaN
2   NaN     NaN     NaN     NaN     15.963645   NaN     NaN     NaN     NaN     16.607557
3   NaN     NaN     0.70016     NaN     NaN     NaN     NaN     0.733307    NaN     NaN
4   NaN     0.761483    NaN     NaN     NaN     NaN     0.787538    NaN     NaN     NaN

>Solution :

You can do that with some stacking:

tmp = df.set_index("Car measurements").stack()
tmp.index = ["_".join(i) for i in tmp.index]
result = tmp.to_frame().T

Why you wanna do that, though, is beyond me, as the original dataframe is a lot easier to analyze.

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