Pandas DataFrame pivot() Method

Rate this post

Preparation

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

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

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 

DataFrame pivot()

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
indexThis 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.
columnsThis parameter can be a string, object, or a list of strings and is optional. Makes up the new DataFrame/Series column(s).
valuesThis 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.

  • A (for Opening Price)
  • B (for Midday Price)
  • C (for Opening Price)
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)
  • Line [1] creates a list of dates and multiplies this by three (3). The output is three (3) entries for each date. This output saves to cdate_idx.
  • Line [2] creates a list of headings for the columns (see above for definitions). Three (3) of each character are required (9 characters). This output saves to group_lst.
  • Line [3] uses np.random.uniform to create a random list of nine (9) numbers between the set range. The output saves to vals_lst.
  • Line [4] creates a DataFrame using all the variables created on lines [1-3]. The output saves to df.
  • Line [5] outputs the DataFrame to the terminal.
  • Line [6] creates a pivot from the DataFrame and groups the data by dates. The output saves to result.
  • Line [7] outputs the result to the terminal.

Output

df

 datesgroupvalue
001/15/2022A9.627767
101/16/2022    A11.528057
201/17/2022    A13.296501
301/15/2022B2.933748
401/16/2022    B2.236752
501/17/2022    B7.652414
601/15/2022C11.813549
701/16/2022    C11.015920
801/17/2022    C0.527554

result

groupABC
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.