- Learn to read and explore CSV data
- Master filtering, grouping, and aggregating data
- Work with dates and time periods
- Calculate totals, averages, and counts
- Prepare data for visualization
Getting Started with Pandas
Pandas is a powerful library for working with data. It reads CSV files and lets you analyze them easily.
Import and Read Data
import pandas as pd
# Read CSV file into a DataFrame
df = pd.read_csv("Task4a_data.csv")
# Display first few rows
print(df.head())
What this does: pd.read_csv() loads the CSV file, df.head() shows first 5 rows
Output placeholder:
Date Car Model New/Used Value Salesperson
0 01/09/2024 Ranger Used 5175 Christopher Clark
1 01/09/2024 Model D Premium Plus New 37316 Christopher Clark
2 03/09/2024 Compass Used 12538 Christopher Clark
3 03/09/2024 Mercury Used 26706 Christopher Clark
4 06/09/2024 Ranger New 18413 Michael Garcia
Exploring Your Data
View Column Names
print(df.columns)
Output: ['Date', 'Car Model', 'New/Used', 'Value', 'Salesperson']
Check Data Shape
print(df.shape) # (rows, columns)
Output: (50, 5) - means 50 rows, 5 columns
View Data Types
print(df.dtypes)
What this does: Shows if columns are text (object), numbers (int64/float64), or dates
Get Basic Statistics
print(df['Value'].describe())
Output placeholder:
count 50.000000
mean 28456.340000
std 14523.120000
min 5175.000000
max 59840.000000
Selecting Data
Select One Column
# Get all values from Value column
values = df['Value']
print(values)
What this does: Returns a Series (single column) of all values
Select Multiple Columns
# Get specific columns
subset = df[['Car Model', 'Value', 'Salesperson']]
print(subset.head())
What this does: Returns a DataFrame with only those 3 columns
Select Rows by Index
# Get first 10 rows
first_ten = df.head(10)
# Get rows 5 to 15
rows_5_to_15 = df[5:16]
Filtering Data
Filtering lets you get specific rows based on conditions.
Filter by One Condition
# Get only New car sales
new_cars = df[df['New/Used'] == 'New']
print(new_cars.head())
What this does: df['New/Used'] == 'New' creates True/False for each row, keeps only True rows
Result: DataFrame with only rows where New/Used is "New"
Filter by Multiple Conditions
# Get New cars sold by Christopher Clark
filtered = df[(df['New/Used'] == 'New') & (df['Salesperson'] == 'Christopher Clark')]
print(filtered)
What this does: & means AND (both conditions must be true), use | for OR
Filter by Value Range
# Get sales over £30,000
high_value = df[df['Value'] > 30000]
# Get sales between £20,000 and £40,000
mid_range = df[(df['Value'] >= 20000) & (df['Value'] <= 40000)]
Filter by List of Values
# Get specific car models
models = ['Ranger', 'Compass']
filtered = df[df['Car Model'].isin(models)]
What this does: .isin(models) checks if Car Model is in the list
Grouping and Aggregating
Grouping combines rows with the same value and calculates totals, averages, counts.
Group by One Column - Sum
# Total sales by car model
model_totals = df.groupby('Car Model')['Value'].sum()
print(model_totals)
What this does: Groups all rows by Car Model, adds up all Values for each model
Output placeholder:
Car Model
Compass 217005
Mercury 212916
Model D Premium Plus 295811
Outback 360573
Ranger 245695
Group by One Column - Count
# Number of sales per salesperson
sales_count = df.groupby('Salesperson')['Value'].count()
print(sales_count)
What this does: Counts how many sales each salesperson made
Group by One Column - Average
# Average sale value per car model
model_avg = df.groupby('Car Model')['Value'].mean()
print(model_avg)
What this does: Calculates average (mean) value for each car model
Group by Multiple Columns
# Total sales by car model AND new/used
grouped = df.groupby(['Car Model', 'New/Used'])['Value'].sum()
print(grouped)
What this does: Groups by both columns, shows totals for each combination
Output placeholder:
Car Model New/Used
Compass New 195114
Used 21891
Mercury New 146618
Used 66298
Model D Premium Plus New 250571
Used 45240
Multiple Aggregations at Once
# Get sum, count, and average for each salesperson
stats = df.groupby('Salesperson')['Value'].agg(['sum', 'count', 'mean'])
print(stats)
What this does: .agg() applies multiple functions at once
Working with Dates
Convert date strings to proper dates for time-based analysis.
Convert to DateTime
# Convert Date column from text to datetime
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
print(df['Date'].head())
What this does: format='%d/%m/%Y' tells Pandas the date format (day/month/year)
Before: "01/09/2024" (text)
After: 2024-09-01 (datetime object)
Extract Month from Date
# Get month from each date
df['Month'] = df['Date'].dt.month
print(df[['Date', 'Month']].head())
What this does: .dt.month extracts month number (9 for September)
Group by Month
# Total sales per month
monthly_sales = df.groupby(df['Date'].dt.to_period('M'))['Value'].sum()
print(monthly_sales)
What this does: .dt.to_period('M') groups dates into months (2024-09, 2024-10)
Group by Week
# Total sales per week
weekly_sales = df.groupby(df['Date'].dt.to_period('W'))['Value'].sum()
print(weekly_sales)
Sorting Data
Sort by Values
# Sort by Value (lowest to highest)
sorted_asc = df.sort_values('Value')
# Sort by Value (highest to lowest)
sorted_desc = df.sort_values('Value', ascending=False)
print(sorted_desc.head())
What this does: ascending=False puts highest values first
Sort Grouped Results
# Get top-selling models
model_totals = df.groupby('Car Model')['Value'].sum().sort_values(ascending=False)
print(model_totals)
Calculating New Columns
Add a New Column
# Add commission column (5% of value)
df['Commission'] = df['Value'] * 0.05
print(df[['Value', 'Commission']].head())
What this does: Creates new column by multiplying Value by 0.05
Cross Tabulation (Crosstab)
Crosstab creates a table showing the relationship between two categories. Perfect for comparing combinations.
When to Use Crosstab
- Compare two categorical variables (e.g., Car Model vs New/Used)
- See counts or totals for each combination
- Create a summary table that's easy to read
- Analyze patterns across categories
Basic Crosstab - Count
# Count of sales for each Car Model and New/Used combination
crosstab_count = pd.crosstab(df['Car Model'], df['New/Used'])
print(crosstab_count)
What this does: Creates a table with Car Models as rows, New/Used as columns, showing count of sales
Output placeholder:
New/Used New Used
Car Model
Compass 6 4
Mercury 6 5
Model D Premium Plus 6 2
Outback 7 3
Ranger 5 6
Crosstab with Totals
# Count with row and column totals
crosstab_totals = pd.crosstab(df['Car Model'], df['New/Used'], margins=True)
print(crosstab_totals)
What this does: margins=True adds "All" row and column showing totals
Output placeholder:
New/Used New Used All
Car Model
Compass 6 4 10
Mercury 6 5 11
Model D Premium Plus 6 2 8
Outback 7 3 10
Ranger 5 6 11
All 30 20 50
Crosstab with Sum of Values
# Total sales value for each combination
crosstab_sum = pd.crosstab(df['Car Model'], df['New/Used'],
values=df['Value'], aggfunc='sum')
print(crosstab_sum)
What this does: values=df['Value'] uses Value column, aggfunc='sum' adds them up
Output placeholder:
New/Used New Used
Car Model
Compass 195114.0 21891.0
Mercury 146618.0 66298.0
Model D Premium Plus 250571.0 45240.0
Outback 238573.0 122000.0
Ranger 161124.0 84571.0
Crosstab with Average
# Average sale value for each combination
crosstab_avg = pd.crosstab(df['Car Model'], df['New/Used'],
values=df['Value'], aggfunc='mean')
print(crosstab_avg)
What this does: aggfunc='mean' calculates average instead of sum
Crosstab with Multiple Aggregations
# Get both sum and count
crosstab_multi = pd.crosstab(df['Car Model'], df['New/Used'],
values=df['Value'], aggfunc=['sum', 'count'])
print(crosstab_multi)
What this does: Shows both total and count for each combination
Practical Example: Salesperson Performance by Category
# See which salespeople sell more New vs Used cars
performance = pd.crosstab(df['Salesperson'], df['New/Used'],
values=df['Value'], aggfunc='sum', margins=True)
print(performance)
Use case: Identify if certain salespeople specialize in New or Used cars
Output placeholder:
New/Used New Used All
Salesperson
Christopher Clark 245000.0 125000.0 370000.0
David Johnson 198000.0 142000.0 340000.0
Michael Garcia 187000.0 98000.0 285000.0
Sarah Jones 262000.0 75000.0 337000.0
All 892000.0 440000.0 1332000.0
Common Task 4a Operations
Compare New vs Used Sales
# Total sales for New vs Used
new_used_totals = df.groupby('New/Used')['Value'].sum()
print(new_used_totals)
# Count of sales for New vs Used
new_used_count = df.groupby('New/Used')['Value'].count()
print(new_used_count)
Top Performing Salespeople
# Total sales per salesperson, sorted
salesperson_totals = df.groupby('Salesperson')['Value'].sum().sort_values(ascending=False)
print(salesperson_totals)
# Get top 3
top_3 = salesperson_totals.head(3)
print(top_3)
Sales by Model and Month
# Convert dates first
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
# Group by model and month
model_monthly = df.groupby(['Car Model', df['Date'].dt.to_period('M')])['Value'].sum()
print(model_monthly)
Filter and Calculate
# Average value of New car sales only
new_cars = df[df['New/Used'] == 'New']
avg_new = new_cars['Value'].mean()
print(f"Average New Car Sale: £{avg_new:,.2f}")
# Total sales by one salesperson
clark_sales = df[df['Salesperson'] == 'Christopher Clark']
clark_total = clark_sales['Value'].sum()
print(f"Christopher Clark Total: £{clark_total:,.2f}")
Displaying Results
Format Numbers
# Display with thousand separators and 2 decimals
total = df['Value'].sum()
print(f"Total Sales: £{total:,.2f}") # £1,532,000.00
What this does: :,.2f adds commas and 2 decimal places
Print Summary Table
# Create summary and display nicely
summary = df.groupby('Car Model')['Value'].agg(['sum', 'count', 'mean'])
summary.columns = ['Total Sales', 'Number of Sales', 'Average Sale']
print(summary)
Quick Reference
Reading Data
pd.read_csv("file.csv")- Load CSV filedf.head()- View first 5 rowsdf.shape- Get (rows, columns)df.columns- List column names
Selecting
df['Column']- Get one columndf[['Col1', 'Col2']]- Get multiple columnsdf.head(10)- Get first 10 rows
Filtering
df[df['Col'] == 'value']- Filter by conditiondf[(condition1) & (condition2)]- Multiple conditions (AND)df[(condition1) | (condition2)]- Multiple conditions (OR)df[df['Col'].isin([list])]- Filter by list
Grouping
df.groupby('Col')['Value'].sum()- Total by groupdf.groupby('Col')['Value'].count()- Count by groupdf.groupby('Col')['Value'].mean()- Average by groupdf.groupby(['Col1', 'Col2'])- Group by multiple columns
Crosstab
pd.crosstab(df['Col1'], df['Col2'])- Count tablepd.crosstab(df['Col1'], df['Col2'], margins=True)- Add totalspd.crosstab(df['Col1'], df['Col2'], values=df['Value'], aggfunc='sum')- Sum valuesaggfunc='mean'- Use for averages instead of sum
Dates
pd.to_datetime(df['Date'], format='%d/%m/%Y')- Convert to datetimedf['Date'].dt.month- Extract monthdf['Date'].dt.to_period('M')- Group by monthdf['Date'].dt.to_period('W')- Group by week
Sorting
df.sort_values('Col')- Sort ascendingdf.sort_values('Col', ascending=False)- Sort descending
Complete Example
import pandas as pd
# Load data
df = pd.read_csv("Task4a_data.csv")
# Convert dates
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
# Analysis 1: Total sales by car model
print("=== Sales by Car Model ===")
model_totals = df.groupby('Car Model')['Value'].sum().sort_values(ascending=False)
for model, total in model_totals.items():
print(f"{model}: £{total:,.2f}")
# Analysis 2: New vs Used comparison
print("\n=== New vs Used Sales ===")
new_used = df.groupby('New/Used')['Value'].agg(['sum', 'count'])
print(new_used)
# Analysis 3: Monthly trend
print("\n=== Monthly Sales ===")
monthly = df.groupby(df['Date'].dt.to_period('M'))['Value'].sum()
print(monthly)
# Analysis 4: Top salesperson
print("\n=== Top Salesperson ===")
top_seller = df.groupby('Salesperson')['Value'].sum().sort_values(ascending=False).head(1)
print(top_seller)
Common Errors and Fixes
KeyError: 'Column'
Problem: Column name doesn't exist or is misspelled
Fix: Check df.columns for exact spelling (case-sensitive!)
TypeError: Cannot compare
Problem: Comparing wrong data types (e.g., text to number)
Fix: Convert data type first: df['Col'].astype(int)
Date not working
Problem: Date is still text, not datetime
Fix: Use pd.to_datetime() with correct format