Re-arrange data stored in rows into columns

Question:

I struggle to put in words what I’m trying to achieve (hence, find what to google) so hopefully an example will help :

I have a dataframe with inventory composition by date, like this:

date    item    quantity
2010   'apple'    10    
2010   'pear'     6    
2010   'berry'     5    
2011   'apple'     8    
2011   'pear'     3    
2011   'lemon'     5    
2011   'berry'     9    

What I’d like is have one line by date, and each item in a column:

date    apple    pear  lemon  berry
2010     10       6             5
2011     8        3      5      9

Any idea?

Asked By: G J

||

Answers:

You are looking to pivot your df.

df = pd.DataFrame({'date': [2010, 2010, 2010, 2011, 2011, 2011, 2011],
                   'item': ['apple', 'pear', 'berry', 'apple', 'pear', 'lemon', 'berry'],
                   'quantity': [10, 6, 5, 8, 3, 5, 9]})
df.pivot(index='date', columns='item', values='quantity')

enter image description here

Answered By: not a robot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.