Pivoting DataFrames

We pivot our data to go from long format to wide format. The pivot() method performs the restructuring of our DataFrame object. In order to pivot, we need to tell pandas which column currently holds the values (with the values argument) and the column that contains what will become the column names in the wide format (the columns argument). Optionally, we can provide a new index (the index argument). Let's pivot into a wide format where we have a column for each of the datatypes that contain the temperature in Celsius and use the dates as the index:

>>> pivoted_df = long_df.pivot(...     index='date', columns='datatype', values='temp_C'... )>>> pivoted_df.head()

In our starting dataframe, there was a datatype column that contained ...

Get Hands-On Data Analysis with Pandas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.