Creating Pivot Tables in Pandas

Creating pivot tables in pandas is like rearranging your data’s furniture to better suit the room’s layout. Let’s rearrange.

Pivot Tables: A Quick Setup

Pivot tables in pandas allow you to summarize and analyze your dataset in a spreadsheet-like format, making it easier to see comparisons, patterns, and trends:

import pandas as pd

# Sample DataFrame
data = {
'Date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02'],
'Category': ['Fruit', 'Vegetable', 'Fruit', 'Vegetable'],
'Product': ['Apple', 'Carrot', 'Banana', 'Broccoli'],
'Amount': [12, 15, 19, 20]
}
df = pd.DataFrame(data)

# Creating a pivot table
pivot = df.pivot_table(values='Amount', index='Category', columns='Date', aggfunc='sum')
print(pivot)

This code example transforms the DataFrame into a pivot table that sums up the amounts by category and date, offering a clear view of daily sales by product type.

Pivoting your data in pandas can transform rows of data into a clear summary report, shining a spotlight on important aspects of your information landscape.

Leave a Reply