Home > Back-end >  Re-arrange data stored in rows into columns
Re-arrange data stored in rows into columns

Time:05-29

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?

CodePudding user response:

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

  • Related