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:
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.