Pandas pivot tables are a powerful tool for summarizing and aggregating data in a data frame. They allow you to transform the data into a more readable and convenient format, and to perform various calculations and operations on the data.
To create a pivot table in Pandas, you can use the pivot_table()
method of a DataFrame. This method takes several arguments, including:
values
: the column or columns to use for the values in the pivot table.index
: the column or columns to use for the rows in the pivot table.columns
: the column or columns to use for the columns in the pivot table.aggfunc
: the aggregation function to use for the values in the pivot table.fill_value
: the value to use for cells that do not have any data.margins
: whether to include row and column totals in the pivot table.
Here’s an example of how you can use the pivot_table()
method to create a pivot table in Pand
import pandas as pd
# Load the data into a DataFrame
df = pd.read_csv('data.csv')
# Create a pivot table showing the total amount spent by city and expense type
pivot = df.pivot_table(values='Amount', index='City', columns='Exp Type', aggfunc='sum', fill_value=0)
# Display the pivot table
print(pivot)
This will create a pivot table with the cities on the rows and the expense types on the columns and the total amount
Here is an example of how you can create a pivot table showing the gender count by city using Pandas:
# Pivot table showing gender count by city
pivot = df.pivot_table(index='City', columns='Gender', values='Amount', aggfunc='count', fill_value=0)
# Display the pivot table
print(pivot)
This will create a pivot table with the cities on the rows and the gender counts on the columns. The fill_value
argument specifies the value to use for cells with no data. In this case, we are using 0 as the fill value.
You can then use the plot()
method to create a bar chart from the pivot table. Here's an example of how you can do this:
import matplotlib.pyplot as plt
# Create a bar chart
pivot.plot(kind='bar')
# Add a title
plt.title('Gender Count by City')
# Show the plot
plt.show()
This will create a bar chart