
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Create a Pivot Table as a DataFrame – Python Pandas
To create a Pivot Table, use the pandas.pivot_table() to create a spreadsheet-style pivot table as a DataFrame.
At first, import the required library −
import pandas as pd
Create a DataFrame with Team records −
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
Create a Pivot Table: with a single column −
pd.pivot_table(dataFrame, index = ["Team ID"])
Example
Following is the code −
import pandas as pd # create DataFrame with Team records dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}}) print"DataFrame...\n",dataFrame print"\n... Pivot ..." print(pd.pivot_table(dataFrame, index = ["Team ID"]))
Output
This will produce the following output −
DataFrame... Team ID Team Name Team Points Team Rank 0 5 India 95 One 1 9 Australia 93 Two 2 6 Bangladesh 42 Six 3 11 South Africa 60 Four 4 2 Sri Lanka 80 Three 5 7 England 55 Five ... Pivot ... Team Points Team ID 2 80 5 95 6 42 7 55 9 93 11 60
- Related Articles
- Create a Pivot Table with multiple columns – Python Pandas
- How to Create a Pivot Table in Python using Pandas?
- Python – Create a new column in a Pandas dataframe
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns
- Python Pandas - Create a Subset DataFrame using Indexing Operator
- Python Pandas - Create Multiindex from dataframe
- Create a Pipeline and remove a column from DataFrame - Python Pandas
- Create a Pandas DataFrame from lists
- Python Pandas - Create a DataFrame from DateTimeIndex ignoring the index
- Create a Pandas Dataframe from a dict of equal length lists in Python
- Python Pandas - Create a DataFrame from original index but enforce a new index
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns but avoid setting the index of the returned DataFrame
- How to create a pandas DataFrame using a list?
- How to create a pandas DataFrame using a dictionary?
- How to append a list as a row to a Pandas DataFrame in Python?

Advertisements