GreenGodot
GreenGodot

Reputation: 6753

Format a dataframe using Python pandas

I have a pandas dataframe that has a format like this

Date       Grade    Student
1/1/2015    0.15    Brian
1/1/2015    0.05    Steve
1/1/2015    0.02    Connor
1/2/2015    0.14    Brian
1/2/2015    0.05    Steve

.....

Is it possible to reformat the dataframe in such a way in that it now looks like this?

Date      Brian   Steve   Connor
1/1/2015   0.15    0.05    0.02
1/2/2015   0.14    0.05     -

I am quite familiar with Pandas and aggregating columns together but am unsure how to go about compressing them in this particular way, any help woiuld be great.

Upvotes: 1

Views: 61

Answers (2)

Alexander
Alexander

Reputation: 109526

In this simple case you can just use pivot.

>>> df.pivot('Date', 'Student', 'Grade')
Student   Brian  Connor  Steve
Date                          
1/1/2015   0.15    0.02   0.05
1/2/2015   0.14     NaN   0.05

Upvotes: 1

Fabio Lamanna
Fabio Lamanna

Reputation: 21552

You can use pivot_table:

a = df.pivot_table(index='Date', columns='Student', values='Grade')

This returns:

Out[5]: 
Student   Brian  Connor  Steve
Date                          
1/1/2015   0.15    0.02   0.05
1/2/2015   0.14     NaN   0.05

Upvotes: 1

Related Questions