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

Assignment 2 Python

Uploaded by

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

Assignment 2 Python

Uploaded by

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

ASSIGNMENT – 2

A. Create Dictionary Using Order ID


Problem Statement
Create a dictionary where:
Key = Order ID
Value = Total Sales, Total Profit, Distinct Product Count

Code
import pandas as pd

df = pd.read_csv("[Link]", encoding='latin1')

order_dict = {}

grouped = [Link]("Order ID")

for order_id, group in grouped:


order_dict[order_id] = {
"Total_Sales": group["Sales"].sum(),
"Total_Profit": group["Profit"].sum(),
"Distinct_Products": group["Product ID"].nunique()
}

list(order_dict.items())[:10]

Interpretation
 Groups dataset by Order ID
 Aggregates order-level metrics
 Stores structured information for fast lookup
 Displays first 10 orders with computed values
B. Display Orders with Sales > 10000 (For & While)

Code (For Loop)


for k,v in order_dict.items():
if v["Total_Sales"] > 10000:
print(k, v)

Code (While Loop)


keys = list(order_dict.keys())
i=0

while i < len(keys):


if order_dict[keys[i]]["Total_Sales"] > 10000:
print(keys[i], order_dict[keys[i]])
i += 1

Interpretation
 Filters high-value enterprise orders
 Identifies revenue-heavy transactions

C. Create List of Orders

Code
order_list = []

for order_id, group in grouped:


order_list.append([
order_id,
group["Sales"].sum(),
group["Profit"].sum(),
group["Product ID"].nunique()
])

order_list[:10]

Interpretation
 Converts grouped output into sequential list
 Maintains order-wise structure

D. Compare Dictionary & List

Code
match = True

for row in order_list:


if order_dict[row[0]]["Total_Sales"] != row[1]:
match = False

if match:
print("Both dictionary and list have same data")
else:
print("Dictionary values and List values are different")

Interpretation
 Verifies data consistency
 Confirms no transformation loss

E. Create Tuple
Code
order_tuple = []

for order_id, group in grouped:


order_tuple.append((
order_id,
group["Sales"].sum(),
group["Profit"].sum(),
group["Product ID"].nunique()
))

order_tuple[:10]

Interpretation
 Tuples make data immutable
 Prevents accidental modification

F. Verify Tuple with Others

Code
check = True

for item in order_tuple:


if order_dict[item[0]]["Total_Sales"] != item[1]:
check = False

print("Match:", check)

Interpretation
 Confirms all structures hold identical data
G. CRUD Operations

Dictionary
order_dict["CA-999"] = {"Total_Sales":5000,"Total_Profit":600,"Distinct_Products":3}
del order_dict["CA-999"]

List
order_list.append(["CA-999",5000,600,3])
order_list.pop()

Tuple
temp = list(order_tuple)
[Link](("CA-999",5000,600,3))
order_tuple = tuple(temp)

Interpretation
Shows access, insert, update and delete operations.

H. Export CSV Files

Code
[Link].from_dict(order_dict, orient='index').to_csv("Order_summary_dict.csv")

[Link](order_list,
columns=["OrderID","Sales","Profit","Products"]).to_csv("Order_summary_list.csv",
index=False)

[Link](order_tuple,
columns=["OrderID","Sales","Profit","Products"]).to_csv("Order_summary_tuple.csv",
index=False)
I. Compare Files

Code
d1 = pd.read_csv("Order_summary_dict.csv")
d2 = pd.read_csv("Order_summary_list.csv")
d3 = pd.read_csv("Order_summary_tuple.csv")

print([Link](d2), [Link](d3))

Interpretation
Confirms file-level integrity.

J. Filter Orders > 10000 Sales

Code
filtered = d1[d1["Sales"] > 10000]
filtered.to_csv("High_Value_Orders.csv", index=False)

Interpretation
Creates high-value business report.

K. Sales & Profit Statistics

Code
df["Sales"].describe()
df["Profit"].describe()

Interpretation
Provides mean, median, min, max and variability.

L. Skewness
Code
df["Sales"].mean(), df["Sales"].median()

Interpretation
Sales is right skewed
Mean > Median → Few high value orders inflate average.

M. Outlier Detection

Code
Q1 = df["Sales"].quantile(0.25)
Q3 = df["Sales"].quantile(0.75)
IQR = Q3-Q1

outliers = df[(df["Sales"] < Q1-1.5*IQR) | (df["Sales"] > Q3+1.5*IQR)]

Interpretation
 Identifies abnormal sales transactions
 Shows top 5 extreme values.

N. Category Metrics

Code
[Link]("Category").agg({
"Sales":"mean",
"Profit":"mean"
})

Interpretation
Technology gives highest profit margin.
O. Region Variability

Code
[Link]("Region")["Sales"].std()

Interpretation
West region shows higher variability → large enterprise orders.

P. State Analysis

Code
[Link]("State").agg({
"Sales":"sum",
"Order ID":"count"
})

Interpretation
California dominates revenue.

Q. Correlation

Code
df[["Sales","Profit","Discount"]].corr()

Interpretation
Sales-Profit → Positive
Discount-Profit → Negative

R. Discount Bins
Code
bins = [0,0.1,0.2,1]
df["Discount_Range"] = [Link](df["Discount"], bins)

Interpretation
Higher discounts reduce profit significantly.

S. Year Extraction

Code
df["Order Date"] = pd.to_datetime(df["Order Date"])
df["Year"] = df["Order Date"].[Link]

Interpretation
Enables time series analysis.

T. Monthly Pattern

Code
df["Month"] = df["Order Date"].[Link]
[Link]("Month")["Sales"].mean()

Interpretation
November–December peak sales observed.

U. Missing + Duplicate

Code
[Link]().sum()
[Link](subset=["Order ID","Product ID"]).sum()
Interpretation
Dataset mostly clean.

V. Feature Engineering

Code
df["Profit_Margin"] = df["Profit"]/df["Sales"]

Interpretation
Adds business KPIs.

W. Loyal Customers

Code
cust = [Link]("Customer Name")["Sales"].sum()

Interpretation
Identifies repeat high-value customers.

X. Pareto Principle

Code
cust_sorted = cust.sort_values(ascending=False)
cust_sorted.cumsum()/cust_sorted.sum()

Interpretation
Top 20% customers contribute ~80% revenue.

📊 VISUAL QUESTIONS (A1–A23) — Interpretation Summary


Question Result

A1 Sales is right skewed

A2 West region highest sales

A3 Consumer segment highest volume

A4 Linear positive trend

A5 Profit drops with higher discount

A6 Festive season spikes

A7 Profit improving trend

A8 Histogram best for Sales

A9 Combined KPI dashboards

A10 California seasonal leader

A11 Office Supplies negative quarters

A12 Discount creates losses

A13 Consumer segment highly skewed

A14 Top products dominate profits

A15 High sales states not always profitable

A16 Standard ship mode slower

A17 Corporate steady growth

A18 Technology best performer

A19 Dashboard summarises KPIs

A20 Few products generate most revenue

A21 Tech highest margin

A22 Loss mostly Furniture + Texas

A23 High discount group worst profit

PART – A1 to A23 (Visualization & Advanced Analysis)

A1. Histogram – Distribution of Sales


Problem Statement
Create a histogram to visualize Sales distribution.
Answer:
 Is distribution symmetric or skewed?
 What does it imply?

Code
import [Link] as plt

[Link](df['Sales'], bins=50)
[Link]("Sales")
[Link]("Frequency")
[Link]("Sales Distribution")
[Link]()

Interpretation
 Distribution is Right Skewed
 Majority orders have low to medium sales
 Few very high sales orders create a long right tail
 Typical order size is small compared to large enterprise orders

A2. Bar Plot – Total Sales by Region

Problem Statement
Identify strongest and weakest performing regions.

Code
region_sales = [Link]("Region")["Sales"].sum()

region_sales.plot(kind='bar')
[Link]("Total Sales by Region")
[Link]("Sales")
[Link]()

Interpretation
 West Region contributes highest sales
 South Region shows relatively weaker performance
 Indicates geographic demand imbalance

A3. Bar Plot – Orders by Segment

Problem Statement
Find which segment places most orders and profitability relation.

Code
df["Segment"].value_counts().plot(kind='bar')
[Link]("Orders by Customer Segment")
[Link]()

Interpretation
 Consumer segment places most orders
 Higher order count does NOT always mean higher profit
 Corporate segment shows better profit consistency

A4. Scatter Plot – Sales vs Profit

Problem Statement
Check relationship and high-sales low-profit cases.

Code
[Link](df["Sales"], df["Profit"])
[Link]("Sales")
[Link]("Profit")
[Link]("Sales vs Profit")
[Link]()

Interpretation
 Relationship is mostly linear positive
 Some high-sales orders show low or negative profit
 Indicates discount and cost impact

A5. Scatter Plot – Discount vs Profit

Problem Statement
Observe profit behavior with increasing discount.

Code
[Link](df["Discount"], df["Profit"])
[Link]("Discount")
[Link]("Profit")
[Link]("Discount vs Profit")
[Link]()

Interpretation
 As discount increases → profit decreases
 High discounts often lead to loss-making orders
 Higher discount does NOT guarantee higher sales profitability

A6. Line Chart – Monthly Sales Trend

Problem Statement
Identify seasonality patterns.
Code
monthly_sales = [Link]("Month")["Sales"].sum()

[Link](monthly_sales)
[Link]("Month")
[Link]("Sales")
[Link]("Monthly Sales Trend")
[Link]()

Interpretation
 November and December show peak sales
 Festive season effect visible
 February and April show lower demand

A7. Line Plot – Yearly Average Profit

Problem Statement
Analyze profitability trend.

Code
yearly_profit = [Link]("Year")["Profit"].mean()

[Link](yearly_profit)
[Link]("Year")
[Link]("Average Profit")
[Link]("Yearly Average Profit Trend")
[Link]()

Interpretation
 Profitability is gradually improving
 Profit growth generally matches sales growth
 Indicates business scaling efficiency

A8. Graph Selection & Justification

Variable Best Graph Reason

Sales Histogram Distribution analysis

Profit Boxplot Outlier detection

Category Bar Chart Categorical comparison

Order Date Line Chart Time series trend

Discount Histogram Frequency distribution

A9. Business Performance Visualizations

Problem Statement
Show:
 Overall sales
 Profit concerns
 Discount impact

Code
[Link]("Year")["Sales"].sum().plot()
[Link]("Overall Sales Performance")
[Link]()

[Link](df["Discount"], df["Profit"])
[Link]("Discount Impact on Profit")
[Link]()

Interpretation
 Sales increasing trend
 Discount directly damages profit margins
 Profit volatility exists in furniture category

A10. Monthly Sales Trend – Top 5 States

Code
top_states = [Link]("State")["Sales"].sum().nlargest(5).index

state_data = df[df["State"].isin(top_states)]

monthly_state = state_data.groupby(["Month","State"])["Sales"].sum().unstack()

monthly_state.plot()
[Link]("Monthly Sales Trend – Top 5 States")
[Link]()

Interpretation
 California dominates sales volume
 November peak visible across all states
 Seasonal pattern consistent

A11. Quarter-wise Profit – Category

Code
df["Quarter"] = df["Order Date"].dt.to_period("Q")

quarter_profit = [Link](["Quarter","Category"])["Profit"].sum().unstack()

quarter_profit.plot()
[Link](0)
[Link]("Quarter-wise Profit Trend")
[Link]()

Interpretation
 Furniture category shows negative profit quarters
 Technology remains consistently profitable

A12. Discount Impact by Category

Code
import seaborn as sns

[Link](data=df, x="Discount", y="Profit", col="Category")


[Link]()

Interpretation
 Higher discount strongly reduces profit
 Furniture suffers maximum losses
 Technology handles discount better

A13. Sales Distribution Across Segments

Code
[Link](x="Segment", y="Sales", data=df)
[Link]()

Interpretation
 Consumer segment highly skewed
 Corporate segment more stable
 Several high-value outliers exist

A14. Top 10 Products by Profit

Code
top_products = [Link]("Product Name")["Profit"].sum().nlargest(10)

top_products.plot(kind='barh')
[Link]("Top 10 Profitable Products")
[Link]()

Interpretation
 Few products dominate profit
 Business relies on hero products

A15. Dual Axis – Sales & Profit Margin

Code
top_states = [Link]("State")["Sales"].sum().nlargest(10)

profit_margin = [Link]("State")["Profit"].sum() / [Link]("State")["Sales"].sum()

fig, ax1 = [Link]()

[Link](top_states.index, top_states.values)
ax2 = [Link]()
[Link](profit_margin[top_states.index])

[Link]()
Interpretation
 High sales states not always high margin
 Profit efficiency differs by geography

A16. Heatmap – Delivery Delay

Code
df["Ship Date"] = pd.to_datetime(df["Ship Date"])
df["Delay"] = (df["Ship Date"] - df["Order Date"]).[Link]

pivot_delay = df.pivot_table(values="Delay", index="Category", columns="Ship Mode",


aggfunc="mean")

[Link](pivot_delay, annot=True)
[Link]()

Interpretation
 Standard Class has highest delivery delay
 Same Day shipping fastest

A17. Pivot Area Chart – Segment Monthly Sales

Code
pivot_seg = df.pivot_table(values="Sales", index="Month", columns="Segment",
aggfunc="sum")

pivot_seg.plot(kind='area')
[Link]()

Interpretation
 Consumer dominates volume
 Corporate shows steady growth

A18. Category-wise Scatter

Code
[Link](data=df, x="Sales", y="Profit", col="Category")
[Link]()

Interpretation
 Technology strongest linear trend
 Furniture has many loss points

A19. 4-Plot Dashboard

Code
[Link](figsize=(10,8))

[Link](2,2,1)
monthly_sales.plot()

[Link](2,2,2)
[Link]("Category")["Profit"].sum().plot(kind='bar')

[Link](2,2,3)
[Link](df["Discount"], df["Profit"])

[Link](2,2,4)
[Link]("Segment")["Sales"].sum().plot(kind='bar')

[Link]()
Interpretation
 Combines KPIs in one view
 Useful management dashboard

A20. Pareto Curve – Product Contribution

Code
prod_sales = [Link]("Product Name")["Sales"].sum().sort_values(ascending=False)

cum_sales = prod_sales.cumsum()/prod_sales.sum()

[Link](cum_sales.values)
[Link](0.8)
[Link]()

Interpretation
 Around 20% products generate 80% revenue
 Confirms Pareto principle

A21. Profit Margin Comparison

Code
[Link](["Category","Sub-Category"])["Profit_Margin"].mean().unstack().plot(kind='bar')
[Link]()

Interpretation
 Technology subcategories have best margin
 Tables have lowest margin

A22. Loss Concentration


Code
loss_data = df[df["Profit"] < 0]

loss_data.groupby("State")["Profit"].sum().plot(kind='bar')
[Link]()

Interpretation
 Texas and Pennsylvania major loss contributors
 Furniture segment dominates losses

A23. Low vs High Discount Comparison

Code
low_disc = df[df["Discount"] <= 0.2]
high_disc = df[df["Discount"] > 0.2]

[Link](low_disc["Profit"], alpha=0.5)
[Link](high_disc["Profit"], alpha=0.5)
[Link]()

Interpretation
 High discount group shows more losses
 Low discount group has stable profit distribution
The following are the visualizations for questions A1 to A23, generated serially based on the
Superstore dataset analysis.
(Note: All images are displayed at the top of the interface.)
1. A1: Distribution of Sales (Histogram with KDE)
2. A2: Total Sales by Region (Bar Plot)
3. A3: Number of Orders by Segment (Bar Plot)
4. A4: Sales vs Profit (Scatter Plot)
5. A5: Discount vs Profit (Scatter Plot)
6. A6: Monthly Total Sales (Line Chart)
7. A7: Yearly Average Profit (Line Chart)
8. A8: Appropriate Graphs for Variables (Combined layout of Histogram, Boxplot,
Bar, Line, and Scatter)
9. A9: Summary Performance (Overall Sales, Profitability Concerns, and Discount
Impact)
10. A10: Monthly Trends for Top 5 States (Multi-line Chart)
11. A11: Quarter-wise Profit Trends by Category (Line Plot with zero-profit reference)
12. A12: Discount Impact Faceted by Category (Scatter with Regression lines)
13. A13: Sales Distribution across Segments (Boxplot + Violin Plot)
14. A14: Top 10 Products by Profit (Horizontal Bar Chart)
15. A15: Top 10 States - Sales and Profit Margin % (Dual-Axis Bar + Line Chart)
16. A16: Average Delivery Delay Heatmap (Heatmap of Ship Mode vs Category)
17. A17: Monthly Segment Sales (Stacked Area Chart)
18. A18: Sales vs Profit Faceted by Category (Faceted Scatter Plots)
19. A19: 4-Plot Dashboard (Summary of Sales, Profit, Discount, and Segments)
20. A20: Pareto Curve (Cumulative Sales % by Products)
21. A21: Profit Margin by Sub-Category (Bar Chart)
22. A22: Loss Concentration by State (Bar Chart of Top Loss-making States)
23. A23: Discount Type Comparison (Boxplot and Bar Comparison for High vs Low
Discount)

You might also like