Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Pandas dataframe with multiple rows into one row

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
like image 320
Daisuke SHIBATO Avatar asked Sep 12 '25 01:09

Daisuke SHIBATO


1 Answers

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
like image 178
jpp Avatar answered Sep 13 '25 15:09

jpp