Home > Net >  How do you create new column from two distinct categorical column values in a dataframe by same colu
How do you create new column from two distinct categorical column values in a dataframe by same colu

Time:05-28

Sorry for the confusing title. I am practicing how to manipulate dataframes in Python through pandas. How do I make this kind of table:

    id   role                      name
0   11  ACTOR       Luna Wedler, Jannis Niewöhner, Milan Peschel, ...
1   11  DIRECTOR    Christian Schwochow
2   22  ACTOR       Guy Pearce, Matilda Anna Ingrid Lutz, Travis F...
3   22  DIRECTOR    Andrew Baird
4   33  ACTOR       Glenn Fredly, Marcello Tahitoe, Andien Aisyah,...
5   33  DIRECTOR    Saron Sakina

Into this kind:

    id  director                       actors name                            
0   11  Christian Schwochow   Luna Wedler, Jannis Niewöhner, Milan Peschel, ...
1   22  Andrew Baird          Guy Pearce, Matilda Anna Ingrid Lutz, Travis F...d
2   33  Saron Sakina          Glenn Fredly, Marcello Tahitoe, Andien Aisyah,...

CodePudding user response:

Try this way

df.pivot(index='id', columns='role', values='name')

CodePudding user response:

You can do in addition to @Tejas's answer:

df = (df.pivot(index='id', columns='role', values='name').
       reset_index().
       rename_axis('',axis=1).
       rename(columns={'ACTOR':'actors name','DIRECTOR':'director'}))
  • Related