0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help!!
If it works, can you mark the answer? The check mark beside the question on the left side. Also, take your time to go through the SO guide and help. Welcome to SO!
The R equivalent reshape2::dcast(df, Name ~ Courses, value.var='Attendence', sum)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.