Pandas DataFrame pivot() Method – Be on the Right Side of Change (original) (raw)


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import numpy as np


The pivot() method reshapes a DataFrame/Series and produces/returns a pivot table based on column values.

The syntax for this method is as follows:

DataFrame.pivot(index=None, columns=None, values=None)

Parameter Description
index This parameter can be a string, object, or a list of strings and is optional. This option makes up the new DataFrame/Series index. If None, the existing index is selected.
columns This parameter can be a string, object, or a list of strings and is optional. Makes up the new DataFrame/Series column(s).
values This parameter can be a string, object, or a list of the previous and is optional.

For this example, we generate 3-day sample stock prices for Rivers Clothing. The column headings display the following characters.

cdate_idx = ['01/15/2022', '01/16/2022', '01/17/2022'] * 3 group_lst = list('AAABBBCCC') vals_lst = np.random.uniform(low=0.5, high=13.3, size=(9))

df = pd.DataFrame({'dates': cdate_idx, 'group': group_lst, 'value': vals_lst}) print(df)

result = df.pivot(index='dates', columns='group', values='value') print(result)

Output

df

| | dates | group | value | | | ------- | ---------- | ----- | --------- | | 0 | 01/15/2022 | A | 9.627767 | | 1 | 01/16/2022 | A | 11.528057 | | 2 | 01/17/2022 | A | 13.296501 | | 3 | 01/15/2022 | B | 2.933748 | | 4 | 01/16/2022 | B | 2.236752 | | 5 | 01/17/2022 | B | 7.652414 | | 6 | 01/15/2022 | C | 11.813549 | | 7 | 01/16/2022 | C | 11.015920 | | 8 | 01/17/2022 | C | 0.527554 |

result

group A B C
dates
01/15/2022 8.051752 9.571285 6.196394
01/16/2022 6.511448 8.158878 12.865944
01/17/2022 8.421245 1.746941 12.896975

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.