1

Sorry if the title is not clear i'm a newbie, hopefully an exemple will make it more understandable. So let's take this DataFrame :

Area     AorB     Population

Hah      A         23
Hah      B         8
Hah      C         78
Ryu      A         150
Ryu      B         61
Ryu      C         17

I'd like to create a dataframe which would have a column with the 2 Areas, 3 columns named Apop, Bpop and Cpop and the corresponding population. It should look like that :

Area     Apop   Bpop   Cpop

Hah      23     8      78
Ryu      150    61     17

It might sounds dumb but i've been searching for hours how to do this D: help.

noph
  • 11
  • 2

2 Answers2

1

Let us try

out = df.pivot(*df).add_suffix('pop').reset_index()

Out[8]: 
AorB Area  Apop  Bpop  Cpop
0     Hah    23     8    78
1     Ryu   150    61    17
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Another way;

df.set_index(['Area','AorB']).unstack().reset_index().droplevel(0, axis=1).add_suffix('pop') 

AorB  pop  Apop  Bpop  Cpop
0     Hah    23     8    78
1     Ryu   150    61    17
wwnde
  • 26,119
  • 6
  • 18
  • 32