0

I need to convert a Pandas dataframe with multiple rows into one row.

Having the following dataframe.

key  value   id    code
A     36.0   NWL   787501
B     38.0   NWL   787501
A     19.0   MOH   978462
B     25.5   MOH   978462
A     92.0   PPC   259280
B     73.7   PPC   259280

I'd like to convert the dataframe to the following format.

A      B      id    code 
36.0   38.0   NWL   787501
19.0   25.5   MOH   978462
92.0   73.7   PPC   259280
Delphi
  • 71
  • 1
  • 8

1 Answers1

0

Try this using dataframe reshaping with set_index, unstack, and reset_index:

df.set_index(['id','code', 'key'])['value'].unstack().reset_index()

Output:

key   id    code     A     B
0    MOH  978462  19.0  25.5
1    NWL  787501  36.0  38.0
2    PPC  259280  92.0  73.7
Scott Boston
  • 147,308
  • 15
  • 139
  • 187