Robin1988
Robin1988

Reputation: 1554

Generate new dataframe with values in old dataframe as new features in python

I have a old data frame like:

Name  Courses      Attendence   Day
Mike    Math           1        Monday
Mike    Math           1        Tuesday
Mike    Physcis        2        Monday
Mike    Chemisty       1        Monday
John    Math           2        Tuesday
John    Physics        1        Tuesday
John    Physics        1        Tursday

And want to create a new dataframe:

Name  Math  Physics  Chemisry
Mike  2        2       1
John  2        2       0

Is there any efficient way to do it?

Thanks!

Upvotes: 0

Views: 148

Answers (1)

Kartik
Kartik

Reputation: 8703

Use pd.pivot_table()

pivoted = pd.pivot_table(data=df, columns='Courses', index='Name',
                         aggfunc='sum', fill_value=0)

Let me know if you run into problems.

Upvotes: 1

Related Questions