Python Pandas - Pivoting



Pivoting in Python Pandas is a powerful data transformation technique that reshapes data for easier analysis and visualization. It changes the data representation from a "long" format to a "wide" format, making it simpler to perform aggregations and comparisons.

This technique is particularly useful when dealing with time series data or datasets with multiple columns. Pandas provides two primary methods for pivoting −

  • pivot(): Reshapes data according to specified column or index values.

  • pivot_table(): It is a more flexible method that allows you to create a spreadsheet-style pivot table as a DataFrame.

In this tutorial, we will learn about the pivoting in Pandas using these methods with examples to demonstrate their applications in data manipulation.

Pivoting with pivot()

The Pandas df.pivot() method is used to reshape data when there are unique values for the specified index and column pairs. It is straightforward and useful when your data is well-structured without duplicate entries for the index/column combination.

Example

Here is a basic example demonstrating pivoting a Pandas DataFrame with the Pandas df.pivot() method.

 import pandas as pd # Create a DataFrame df = pd.DataFrame({"Col1": range(12),"Col2": ["A", "A", "A", "B", "B","B", "C", "C", "C", "D", "D", "D"], "date": pd.to_datetime(["2024-01-03", "2024-01-04", "2024-01-05"] * 4)}) # Display the Input DataFrame print('Original DataFrame:\n', df) # Pivot the DataFrame pivoted = df.pivot(index="date", columns="Col2", values="Col1") # Display the output print('Pivoted DataFrame:\n', pivoted) 

Following is the output of the above code −

 Original DataFrame: 
Col1Col2date
00A2024-01-03
11A2024-01-04
22A2024-01-05
33B2024-01-03
44B2024-01-04
55B2024-01-05
66C2024-01-03
77C2024-01-04
88C2024-01-05
99D2024-01-03
1010D2024-01-04
1111D2024-01-05
Pivoted DataFrame:
Col2ABCD
date
2024-01-030369
2024-01-0414710
2024-01-0525811

Note: The pivot() method requires that the index and columns specified have unique values. If your data contains duplicates, you should use the pivot_table() method instead.

Pivoting with pivot_table()

The pivot() method is a straightforward way to reshape data, while pivot_table() offers flexibility for aggregation, making it suitable for more complex data manipulation tasks. This is particularly useful for summarizing data when dealing with duplicates and requires aggregation of data.

Example

This example demonstrates pivoting a DataFrame using the df.pivot_table() method.

 import numpy as np import pandas as pd import datetime # Create a DataFrame df = pd.DataFrame({"A": [1, 1, 2, 3] * 6, "B": ["A", "B", "C"] * 8, "C": ["x", "x", "x", "y", "y", "y"] * 4, "D": np.random.randn(24), "E": np.random.randn(24), "F": [datetime.datetime(2013, i, 1) for i in range(1, 13)] +[datetime.datetime(2013, i, 15) for i in range(1, 13)]}) # Display the Input DataFrame print('Original DataFrame:\n', df) # Pivot the DataFrame pivot_table = pd.pivot_table(df, values="D", index=["A", "B"], columns=["C"]) # Display the output print('Pivoted DataFrame:\n', pivot_table) 

Following is the output of the above code −

 Original DataFrame: 
ABCDEF
01Ax-0.5303952.8199762013-01-01
11Bx-0.5933470.6398772013-02-01
22Cx0.817982-0.2704992013-03-01
33Ay-1.4380481.7077902013-04-01
41By0.207012-0.3873642013-05-01
51Cy0.4625501.1452602013-06-01
62Ax3.032849-0.0278882013-07-01
73Bx-0.972964-0.5468192013-08-01
81Cx0.613289-0.0417062013-09-01
91Ay-1.072169-0.0618432013-10-01
102By1.3054000.4639812013-11-01
113Cy-1.265300-2.0201582013-12-01
121Ax0.165842-0.1541732013-01-15
131Bx-1.038789-0.7059482013-02-15
142Cx0.6906390.8438552013-03-15
153Ay-0.5922020.7182812013-04-15
161By0.048085-1.1119172013-05-15
171Cy1.111408-0.1252142013-06-15
182Ax0.0860120.2760062013-07-15
193Bx-1.043673-0.7770432013-08-15
201Cx-0.4718180.7369212013-09-15
211Ay-0.138187-0.8491342013-10-15
222By-2.286761-2.8592582013-11-15
233Cy0.392779-0.1047372013-12-15
Pivoted DataFrame: C x y A B 1 A -0.182276 -0.605178 B -0.816068 0.127548 C 0.070736 0.786979 2 A 1.559430 NaN B NaN -0.490681 C 0.754310 NaN 3 A NaN -1.015125 B -1.008318 NaN C NaN -0.436260

Pivoting with Aggregation

The Pandas pivot_table() method can be used to specify an aggregation function. By default it calculates the mean, but you can also use functions like sum, count, or even custom functions for applying aggregation to the pivoting.

Example

This example demonstrates how to apply aggregation function with pivoting a DataFrame using the df.pivot_table() method.

 import numpy as np import datetime import pandas as pd # Create a DataFrame df = pd.DataFrame({"A": [1, 1, 2, 3] * 6, "B": ["A", "B", "C"] * 8, "C": ["x", "x", "x", "y", "y", "y"] * 4, "D": np.random.randn(24), "E": np.random.randn(24), "F": [datetime.datetime(2013, i, 1) for i in range(1, 13)] +[datetime.datetime(2013, i, 15) for i in range(1, 13)]}) # Display the Input DataFrame print('Original DataFrame:\n', df) # Pivot the DataFrame with a aggregate function pivot_table = pd.pivot_table(df, values=["D", "E"], index=["B"], columns=["A", "C"], aggfunc="sum") # Display the output print('Pivoted DataFrame:\n', pivot_table) 

Following is the output of the above code −

 Original DataFrame: 
ABCDEF
01Ax0.9217280.8077992013-01-01
11Bx0.565152-0.3699472013-02-01
22Cx1.2601140.3528442013-03-01
33Ay-1.3696451.5041982013-04-01
41By0.882293-1.1776862013-05-01
51Cy0.5609401.1261212013-06-01
62Ax1.4963090.1316232013-07-01
73Bx0.5571941.5456352013-08-01
81Cx0.518436-0.5811132013-09-01
91Ay-0.607266-1.0326992013-10-01
102By-0.665019-0.6286372013-11-01
113Cy2.146093-0.1757482013-12-01
121Ax0.2035051.4024642013-01-15
131Bx0.6026301.0280112013-02-15
142Cx-0.1378400.0992522013-03-15
153Ay1.5176781.0276512013-04-15
161By-0.949576-0.2686562013-05-15
171Cy-0.328505-0.0928412013-06-15
182Ax0.0893150.7716532013-07-15
193Bx1.889772-0.3482582013-08-15
201Cx1.081143-0.0063872013-09-15
211Ay0.2237910.9443542013-10-15
222By0.111047-1.6349852013-11-15
233Cy-1.4754210.5868252013-12-15
Pivoted DataFrame: D ... E A 1 2 ... 2 3 C x y x ... y x y B ... A 1.125233 -0.383475 1.585623 ... NaN NaN 2.531849 B 1.167782 -0.067283 NaN ... -2.263622 1.197377 NaN C 1.599579 0.232435 1.122273 ... NaN NaN 0.411078 [3 rows x 12 columns]
Advertisements
close