pandas.pivot(index, columns, values) function produces a pivot table based on 3 columns of the DataFrame. Uses unique values from the index/columns and fills them with values.
Python Pandas.pivot() Syntax
Syntax: pandas.pivot(index, columns, values)
Parameters:
- index[ndarray] : Labels to use to make new frame’s index
- columns[ndarray] : Labels to use to make new frame’s columns
- values[ndarray] : Values to use for populating new frame’s values
Returns: Reshaped DataFrame
Exception: ValueError raised if there are any duplicates.
Creating a Sample DataFrame
Here, we are making a sample DataFrame that we will use in our article throughout.
Python3
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'Boby', 'Mina'],
'B': ['Masters', 'Graduate', 'Graduate'],
'C': [27, 23, 21]})
df
Output
A B C
0 John Masters 27
1 Boby Graduate 23
2 Mina Graduate 21
Pandas pivot() Function Examples
Below are some examples by which we can pivot a DataFrame using Pandas pivot() function in Python:
- Creating and Pivot a DataFrame
- Creating a Multi-level Pivot Table with Pandas DataFrame
- ValueError in Pivot a DataFrame
Creating and Pivot a DataFrame
In this example, a pandas DataFrame (df
) is pivoted with columns 'A' and 'B' becoming the new index and columns, respectively, and the values in column 'C' populating the cells of the resulting pivot table. The function assumes that each combination of 'A' and 'B' has a unique corresponding value in 'C'.
Python3
# values can be an object or a list
df.pivot('A', 'B', 'C')
Output
B Graduate Masters
A
Boby 23.0 NaN
John NaN 27.0
Mina 21.0 NaN
Creating a Multi-level Pivot Table with Pandas DataFrame
In this example, the pandas DataFrame (df
) is transformed into a multi-level pivot table, using 'A' as the index, 'B' as the columns, and extracting values from both columns 'C' and 'A' to fill the cells. This approach allows for a more detailed representation of the data, incorporating multiple dimensions into the resulting pivot table.
Python3
# value is a list
df.pivot(index='A', columns='B', values=['C', 'A'])
Output
C A
B Graduate Masters Graduate Masters
A
Boby 23.0 NaN NaN NaN
John NaN 27.0 NaN NaN
Mina 21.0 NaN NaN NaN
ValueError Raised in Pivoting a DataFrame
Raise ValueError when there are any index, columns combinations with multiple values.
Python3
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'John', 'Mina'],
'B': ['Masters', 'Masters', 'Graduate'],
'C': [27, 23, 21]})
df.pivot('A', 'B', 'C')
Output
ValueError: Index contains duplicate entries, cannot reshape
Similar Reads
Pandas.pivot_table() - Python pandas.pivot_table() function allows us to create a pivot table to summarize and aggregate data. This function is important when working with large datasets to analyze and transform data efficiently. In this article, we will see some examples to see how it works.Lets see a example:Pythonimport panda
3 min read
Python | Pandas Panel.sum() In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. Panel.sum() function is used to return the sum of the v
2 min read
Python | Pandas.melt() To make the analysis of data in a table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the functions to do so.. Pandas.melt() unpivots a DataFrame from wide format to long format. Pandas melt() function is useful to massage a DataFr
3 min read
Pivot Tables in Pandas In this article, we will see the Pivot Tables in Pandas. Let's discuss some concepts: Pandas : Pandas is an open-source library that is built on top of the NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is
3 min read
How to Use Python Pandas to manipulate and analyze data efficientlyPandas is a Python toolbox for working with data collections. It includes functions for analyzing, cleaning, examining, and modifying data. In this article, we will see how we can use Python Pandas with the help of examples.What is Python Pandas?A Python lib
5 min read
Python | Pandas Series.mul() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.mul() is used to multiply series or list like objects with same length w
3 min read
Python | Pandas Series.div() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.div() is used to divide series or list like objects with same length by
2 min read
Python | Pandas Series.add() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.add() is used to add series or list like objects with same length to the
2 min read
Pandas Tutorial Pandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
Python PySpark pivot() Function The pivot() function in PySpark is a powerful method used to reshape a DataFrame by transforming unique values from one column into multiple columns in a new DataFrame, while aggregating data in the process. The function takes a set of unique values from a specified column and turns them into separa
4 min read