0% found this document useful (0 votes)
3 views6 pages

Python Assignment 4

The document outlines a data analysis process using a bakery sales dataset, including data exploration, cleaning, sales analysis, revenue generation, time-based analysis, product sales visualization, and correlation analysis. Key findings include identifying the most sold products, total revenue contributions, and sales trends over the week. The analysis is supported by visualizations created using Matplotlib and Seaborn.

Uploaded by

darshanpatil2605
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Python Assignment 4

The document outlines a data analysis process using a bakery sales dataset, including data exploration, cleaning, sales analysis, revenue generation, time-based analysis, product sales visualization, and correlation analysis. Key findings include identifying the most sold products, total revenue contributions, and sales trends over the week. The analysis is supported by visualizations created using Matplotlib and Seaborn.

Uploaded by

darshanpatil2605
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5/8/25, 11:51 AM Rough work.

ipynb - Colab

1) Data Exploration: Load the dataset and display the first few rows. What are the columns present in the dataset? Check for null values and
provide a summary of the dataset.

import pandas as pd

# Load the dataset


df = pd.read_csv('/content/drive/MyDrive/[Link]')

# Display the first few rows of the dataset


print("First few rows of the dataset:")
print([Link]())

# List the columns present in the dataset


print("\nColumns in the dataset:")
print([Link])

# Check for missing values in each column


print("\nMissing values in each column:")
print([Link]().sum())

# Provide summary statistics of the dataset


print("\nSummary statistics of the dataset:")
print([Link]())

First few rows of the dataset:


TransactionNo Items DateTime Daypart DayType Quantity \
0 1 Bread 30-10-2016 09:58 Morning Weekend 5
1 2 Scandinavian 30-10-2016 10:05 Morning Weekend 1
2 2 Scandinavian 30-10-2016 10:05 Morning Weekend 1
3 3 Hot chocolate 30-10-2016 10:07 Morning Weekend 4
4 3 Jam 30-10-2016 10:07 Morning Weekend 3

Price
0 35
1 43
2 43
3 97
4 96

Columns in the dataset:


Index(['TransactionNo', 'Items', 'DateTime', 'Daypart', 'DayType', 'Quantity',
'Price'],
dtype='object')

Missing values in each column:


TransactionNo 0
Items 0
DateTime 0
Daypart 0
DayType 0
Quantity 0
Price 0
dtype: int64

Summary statistics of the dataset:


TransactionNo Quantity Price
count 20507.000000 20507.000000 20507.000000
mean 4976.202370 2.998147 51.027454
std 2796.203001 1.415246 17.976061
min 1.000000 1.000000 31.000000
25% 2552.000000 2.000000 39.000000
50% 5137.000000 3.000000 43.000000
75% 7357.000000 4.000000 57.000000
max 9684.000000 5.000000 99.000000

2) Data Cleaning: Are there any missing or duplicate values in the dataset? If so, clean the data accordingly.

# Display the first few rows to understand the structure


print("First few rows of the dataset:")
print([Link]())

# Check for missing values


missing_values = [Link]().sum()

# Print columns with missing values


print("\nMissing values in each column:")
print(missing_values)

# Handle missing values:

[Link] 1/6
5/8/25, 11:51 AM Rough [Link] - Colab
# For numerical columns (Quantity, Price), we can replace missing values with the median.
df['Quantity'].fillna(df['Quantity'].median(), inplace=True)
df['Price'].fillna(df['Price'].median(), inplace=True)

# For categorical columns (Items, Daypart, DayType), we can replace missing values with the mode (most frequent value).
df['Items'].fillna(df['Items'].mode()[0], inplace=True)
df['Daypart'].fillna(df['Daypart'].mode()[0], inplace=True)
df['DayType'].fillna(df['DayType'].mode()[0], inplace=True)

# # For DateTime column, if it's missing, it can be replaced with a placeholder date (or dropped, depending on use case).
# df['DateTime'].fillna('Unknown', inplace=True)

# Check for duplicate rows


duplicate_rows = [Link]().sum()

# Print the number of duplicate rows


print("\nNumber of duplicate rows:", duplicate_rows)

# Remove duplicate rows if any


df.drop_duplicates(inplace=True)

# Verify that missing values and duplicates are handled


print("\nAfter cleaning:")
print([Link]().sum()) # Check for remaining missing values
print("\nNumber of duplicate rows after cleaning:", [Link]().sum())

# Display the first few rows again after cleaning


print("\nFirst few rows after cleaning:")
print([Link]())

Items 0 
DateTime 0
Daypart 0
DayType 0
Quantity 0
Price 0
dtype: int64

Number of duplicate rows: 0

After cleaning:
TransactionNo 0
Items 0
DateTime 0
Daypart 0
DayType 0
Quantity 0
Price 0
dtype: int64

Number of duplicate rows after cleaning: 0

First few rows after cleaning:


TransactionNo Items DateTime Daypart DayType Quantity \
0 1 Bread 30-10-2016 09:58 Morning Weekend 5
1 2 Scandinavian 30-10-2016 10:05 Morning Weekend 1
3 3 Hot chocolate 30-10-2016 10:07 Morning Weekend 4
4 3 Jam 30-10-2016 10:07 Morning Weekend 3
5 3 Cookies 30-10-2016 10:07 Morning Weekend 3

Price
0 35
1 43
3 97
4 96
5 72
<ipython-input-26-38dd57f669c1>:14: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setti

df['Items'] fillna(df['Items'] mode()[0] inplace=True) 


[Link] 2/6
5/8/25, 11:51 AM Rough [Link] - Colab
df[ Items ].fillna(df[ Items ].mode()[0], inplace=True)

3) Sales Analysis: Which product is the most sold item in the bakery? Show the top 5 products based on sales volume. (hint sort the datframe
in descending order, store it in a new dataframe and then use head function on it)

# Group the data by 'Items' (product) and calculate the total sales volume (sum of Quantity)
sales_volume = [Link]('Items')['Quantity'].sum().reset_index()

# Sort the products by sales volume in descending order


sorted_sales = sales_volume.sort_values(by='Quantity', ascending=False)

# Get the top 5 most sold products


top_5_products = sorted_sales.head(5)

# Display the top 5 products


print("Top 5 products based on sales volume:")
print(top_5_products)

Top 5 products based on sales volume:


Items Quantity
23 Coffee 15763
11 Bread 9811
83 Tea 4162
15 Cake 3023
65 Pastry 2592

4) Revenue Generation: Calculate the total revenue generated by each product. Which product contributed the most to the bakery’s revenue?

# Calculate revenue for each transaction (Quantity * Price)


df['Revenue'] = df['Quantity'] * df['Price']

# Group the data by 'Items' and calculate total revenue for each product
revenue_by_product = [Link]('Items')['Revenue'].sum().reset_index()

# Sort the products by total revenue in descending order


sorted_revenue = revenue_by_product.sort_values(by='Revenue', ascending=False)

# Get the product that contributed the most to the bakery’s revenue
top_revenue_product = sorted_revenue.head(1)

# Display the product with the highest revenue


print("Product that contributed the most to the bakery’s revenue:")
print(top_revenue_product)

# Optionally, display the top 5 products based on revenue


top_5_revenue_products = sorted_revenue.head(5) 
print("\nTop
 5 products based on revenue:") 
print(top_5_revenue_products)

Product that contributed the most to the bakery’s revenue:


Items Revenue
23 Coffee 677809

Top 5 products based on revenue:


Items Revenue
23 Coffee 677809
11 Bread 343385
48 Hot chocolate 171884
83 Tea 162318
15 Cake 148127

5) Time-based Analysis: Analyze sales trends over time. Which day of the week had the highest sales volume? Provide a visualization using
Matplotlib.

import [Link] as plt

# Convert the 'DateTime' column to datetime format


df['DateTime'] = pd.to_datetime(df['DateTime'])

# Extract the day of the week from the 'DateTime' column (0 = Monday, 6 = Sunday)
df['DayOfWeek'] = df['DateTime'].[Link]

# Group the data by 'DayOfWeek' and calculate total sales volume (sum of 'Quantity') for each day
l b d df b (' f k')[' i '] () i d ()
[Link] 3/6
5/8/25, 11:51 AM Rough [Link] - Colab
sales_by_day = [Link]('DayOfWeek')['Quantity'].sum().reset_index()

# Map numeric days to actual day names


sales_by_day['DayName'] = sales_by_day['DayOfWeek'].map({0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday',
4: 'Friday', 5: 'Saturday', 6: 'Sunday'})

# Sort the data by sales volume in descending order


sales_by_day_sorted = sales_by_day.sort_values(by='Quantity', ascending=False)

# Plot the sales volume for each day of the week


[Link](figsize=(10, 6))
[Link](sales_by_day_sorted['DayName'], sales_by_day_sorted['Quantity'], color='skyblue')

# Adding titles and labels


[Link]('Sales Volume by Day of the Week', fontsize=14)
[Link]('Day of the Week', fontsize=12)
[Link]('Total Sales Volume', fontsize=12)
[Link](rotation=45)
plt.tight_layout()

# Show the plot


[Link]()

# Display the day with the highest sales volume


print("Day with the highest sales volume:")
print(sales_by_day_sorted.head(1))

<ipython-input-29-f404eaa81e39>:5: UserWarning: Parsing dates in %d-%m-%Y %H:%M format when dayfirst=False (the default) was specifi
df['DateTime'] = pd.to_datetime(df['DateTime'])

Day with the highest sales volume:


DayOfWeek Quantity DayName
5 5 10453 Saturday

6) Product Sales Visualization: Create a bar chart using Seaborn to visualize the sales of the top 10 products.

import seaborn as sns


import [Link] as plt

# Group the data by 'Items' and calculate total sales volume (sum of 'Quantity') for each product
sales_by_product = [Link]('Items')['Quantity'].sum().reset_index()

# Sort the products by sales volume in descending order and get the top 10 products
top_10_products = sales_by_product.sort_values(by='Quantity', ascending=False).head(10)

# Create a Seaborn bar plot to visualize the sales of the top 10 products

[Link] 4/6
5/8/25, 11:51 AM Rough [Link] - Colab
[Link](figsize=(10, 6))
[Link](x='Quantity', y='Items', data=top_10_products, palette='viridis')

# Adding titles and labels


[Link]('Top 10 Products by Sales Volume', fontsize=14)
[Link]('Sales Volume (Quantity)', fontsize=12)
[Link]('Product', fontsize=12)
plt.tight_layout()

# Show the plot


[Link]()

<ipython-input-30-b0e4bf0ffe39>:14: FutureWarning:

Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `y` variable to `hue` and set `le

[Link](x='Quantity', y='Items', data=top_10_products, palette='viridis')

 

7) Correlation Analysis: If the dataset contains numerical features, analyze the correlation between them. Create a heatmap using Seaborn to
show the correlations.

# Select numerical columns for correlation analysis


numerical_columns = df.select_dtypes(include=['float64', 'int64']).columns

# Calculate the correlation matrix


correlation_matrix = df[numerical_columns].corr()

# Create a heatmap to visualize the correlations


[Link](figsize=(10, 8))
[Link](correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5, vmin=-1, vmax=1)

# Adding title and labels


[Link]('Correlation Heatmap', fontsize=14)
plt.tight_layout()

# Show the plot


[Link]()

[Link] 5/6
5/8/25, 11:51 AM Rough [Link] - Colab

Start coding or generate with AI.

[Link] 6/6

You might also like