Will Will - 2 months ago 28
Python Question

Reorganizing extraneous data in pandas

I have a dataframe organized like this...

**Name** | **Mealtime** | **Food**
John | 8:00 am | cereal
John | 1:00 pm | salad
John | 6:00 pm | pasta
Sara | 8:00 am | yogurt
Sara | 1:00 pm | panini
Sara | 6:00 pm | steak
Jake | 8:00 am | coffee
Jake | 1:00 pm | burrito
Jake | 6:00 pm | salad


And I need it to be organized like this

____| 8:00 am | 1:00 pm | 6:00 pm
John | cereal | salad | pasta
Sara | yogurt | panini | steak
Jake | coffee | burrito | salad


How would I go about doing that? Note that I am not looking for an aesthetic change. Eventually I would like to select rows of data to feed into a for loop in such a way as the name can be determined from the specific food entry. For example, having grabbed the "1:00 pm" column, "salad" would direct me to John. But if I had grabbed the "6:00 pm" column, "salad" would direct me to Jake.

Answer Source

You need df.pivot:

In [606]: df.pivot(index='Name', columns='Mealtime', values='Food')
Out[606]: 
Mealtime  1:00 pm 6:00 pm 8:00 am
Name                             
Jake      burrito   salad  coffee
John        salad   pasta  cereal
Sara       panini   steak  yogurt