I need to convert a Pandas dataframe with multiple rows into one row.
Having the following dataframe.
X Y V
A 0 0.1
A 1 0.2
B 0 0.3
B 1 0.4
I'd like to convert the dataframe to the following format. V_0
means "Value where Y=0
". How to achieve this transformation?
X V_0 V_1
A 0.1 0.2
B 0.3 0.4
Using pd.DataFrame.pivot
:
res = df.pivot(index='X', columns='Y').add_prefix('V_')
res.columns = res.columns.droplevel(0)
res = res.reset_index()
print(res)
Y X V_0 V_1
0 A 0.1 0.2
1 B 0.3 0.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With