Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

What is the pivot function in pandas?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The pivot function in pandas is used to reshape the given data frame based on specific columns. Specified columns act as pivots of the data frame. An important thing to note is that the pivot function does not support data aggregation. Instead, multiple columns will return the data frame, becoming multi-indexed.

Syntax

The pivot function has the following syntax:

pandas.pivot(data, index=None, columns=None, values=None)

Parameters

The pivot function has the following parameters:

Parameters Description
data The data frame passed.
index The columns that will be used to make the index of the new data frame. By default, it is None. The existing index is used in that case.
columns The columns that will exist in the new data frame.
values The column(s) to use to populate the new frame’s values. If unspecified, all remaining columns will be used.

The data and columns parameters are compulsory.

All other parameters are optional.

Return value

The pivot function returns a reshaped data frame according to the provided columns.

Raising errors

An error occurs when there are any index or column combinations with multiple values.

Example

The code snippet below shows how we can use the pivot function in pandas:

import pandas as pd
import numpy as np 

df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two','two'],
      'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
      'baz': [1, 2, 3, 4, 5, 6],
      'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
print("Original Dataframe")
print(df)
print('\n')
print('Reshaped')
print(df.pivot(index ='foo', columns = 'bar', values = 'baz'))
print('\n')

RELATED TAGS

pandas
python

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring