Pandas Reshape Dataframe By Adding A Column Level Based On The Value Of Another Column
I have a pandas dataframe and I would like to add a column level to split specific columns (metric_a, metric_b, metric_c) into several subcolumns based on the value of another colu
Solution 1:
IIUC, use DataFrame.set_index
and unstack
, and reset_index
specifying col_level
parameter:
df.set_index(['participant', 'param']).unstack('param').reset_index(col_level=0)
[out]
participant metric_a metric_b metric_c
param ababab0 alice 0,7000,7360,9120,2300,3410,3701 bob 0,8860,5100,3640,7040,9950,9902 charlie 0,1730,0850,4620,9500,7090,8073 david 0,676 NaN 0,653 NaN 0,189 NaN
4 heidi NaN 0,823 NaN 0,524 NaN 0,430
Post a Comment for "Pandas Reshape Dataframe By Adding A Column Level Based On The Value Of Another Column"