import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="whitegrid") plt.rcParams["figure.figsize"] = (10, 5)
Analyse the given dataset completely and perform the following questions.
Data Analysis Project by Anushka Khemaria, Team edSlash.
We will inspect the raw data, clean errors, create useful columns, group products, explore trends, answer business questions and explain what the results mean.
This project uses the SalesAnalysis.csv file supplied with the lesson. It contains electronic-product sales records from a US retailer. Each row describes a product line in an order and includes an order ID, product name, quantity, unit price, order date and purchase address.
Exploratory Data Analysis is the process of looking at data before making decisions or building a model. We check its shape, types, missing values, strange records, patterns and relationships.
A chart is useful only when we can explain the question it answers.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="whitegrid") plt.rcParams["figure.figsize"] = (10, 5)
Pandas handles tables; NumPy supports numerical work; Matplotlib and Seaborn create charts.
# Put SalesAnalysis.csv in the same folder as this notebook.
df = pd.read_csv("SalesAnalysis.csv")
df.head()| Order ID | Product | Quantity Ordered | Price Each | Order Date | Purchase Address |
|---|---|---|---|---|---|
| 176558 | USB-C Charging Cable | 2 | 11.95 | 04/19/19 08:46 | 917 1st St, Dallas, TX 75001 |
| 176559 | Bose SoundSport Headphones | 1 | 99.99 | 04/07/19 22:30 | 682 Chestnut St, Boston, MA 02215 |
| 176560 | Google Phone | 1 | 600 | 04/12/19 14:38 | 669 Spruce St, Los Angeles, CA 90001 |
Cleaning is important because incorrect rows and data types can make our totals and charts wrong. The PDF manually collected row numbers to remove. That approach is hard to repeat and can break if the file changes. We can identify the same problems using the values in the columns.
df.dtypes df.info()
The raw file stores all six columns as object (text). Quantity and price need numeric types, and Order Date needs a datetime type. Order ID can be kept as text if it is only an identifier; it does not need mathematical operations.
The file contains rows where the values are actually the column names. For example, the Product field contains the word Product 355 times. These are not real sales.
df["Product"].value_counts().head(20) df[df["Quantity Ordered"] == "Quantity Ordered"].head()
355 repeated header records are present. The correct fix is to filter them using a condition, rather than hard-coding hundreds of row indexes.
# Work on a copy so the raw dataframe stays available.
data = df.copy()
# Remove fully blank rows.
data = data.dropna(how="all")
# Remove repeated header rows wherever they occur.
data = data[data["Product"].ne("Product")].copy()
# Convert fields safely. Invalid text becomes missing (NaN).
data["Quantity Ordered"] = pd.to_numeric(
data["Quantity Ordered"], errors="coerce"
)
data["Price Each"] = pd.to_numeric(
data["Price Each"], errors="coerce"
)
data["Order Date"] = pd.to_datetime(
data["Order Date"], format="%m/%d/%y %H:%M", errors="coerce"
)
# Remove rows missing fields needed for this analysis.
required = [
"Order ID", "Product", "Quantity Ordered",
"Price Each", "Order Date", "Purchase Address"
]
data = data.dropna(subset=required).copy()
# Convert quantity to an integer.
data["Quantity Ordered"] = data["Quantity Ordered"].astype("int64")
# Keep order IDs as strings: they are labels, not measured quantities.
data["Order ID"] = data["Order ID"].astype(str)After removing 545 blank rows, 355 repeated headers and records with invalid required values, 185,950 valid rows remain before duplicate checking.
data.isna().sum() data.duplicated().sum() # Remove exact duplicate rows only. data = data.drop_duplicates().copy() data.shape
The file has 264 exact duplicate rows after the invalid rows are removed. Dropping these leaves 185,686 records.
An order ID can appear in several rows when a customer buys several products. Do not drop rows just because Order ID repeats. We remove only fully identical rows.
Now we add columns that make the dataset easier to analyse. These are derived from the original fields, so the original information is still available.
The original PDF suggests converting text-based categorical columns to numbers. This needs one important clarification: product names and cities are labels, not quantities. Giving them arbitrary numbers can make a model think one product is “greater” than another. Keep labels as text for EDA. For machine learning, use one-hot encoding for unordered categories, or another suitable encoding method.
# Convert measured fields to numeric types.
data["Quantity Ordered"] = pd.to_numeric(data["Quantity Ordered"])
data["Price Each"] = pd.to_numeric(data["Price Each"])
# Example: one-hot encode Product only when a model needs numeric inputs.
product_encoded = pd.get_dummies(
data["Product"], prefix="product", dtype=int
)
# Do not replace Product names with arbitrary numbers for ordinary EDA.data["Order Date"] = pd.to_datetime(data["Order Date"])
data["Day"] = data["Order Date"].dt.day
data["Month"] = data["Order Date"].dt.month
data["Year"] = data["Order Date"].dt.year
data["Time"] = data["Order Date"].dt.strftime("%H:%M")
data["Hour"] = data["Order Date"].dt.hour
data["Month Name"] = data["Order Date"].dt.month_name()
data[["Order Date", "Day", "Month", "Year", "Time"]].head()Keep the original price for accurate revenue calculations. Create a separate rounded column only for display or grouping.
data["Price Rounded"] = data["Price Each"].round().astype("int64")
data[["Price Each", "Price Rounded"]].head()# US addresses in this dataset use five-digit ZIP codes.
data["PIN Code"] = data["Purchase Address"].str.extract(
r"(\d{5})(?:-\d{4})?$"
)
data[["Purchase Address", "PIN Code"]].head()data["City"] = (
data["Purchase Address"]
.str.split(",")
.str[1]
.str.strip()
)
data[["Purchase Address", "City"]].head()We create broad groups to compare similar products. This grouping is a practical choice for this dataset, not a universal product taxonomy.
def assign_category(product):
if "Phone" in product:
return "Phones"
elif "Headphones" in product:
return "Headphones"
elif "Cable" in product or "Batteries" in product:
return "Accessories"
elif "Monitor" in product:
return "Monitors"
elif "Laptop" in product:
return "Laptops"
elif product in ["LG Washing Machine", "LG Dryer", "Flatscreen TV"]:
return "Home Appliances & TVs"
return "Other"
data["Category"] = data["Product"].apply(assign_category)
data[["Product", "Category"]].drop_duplicates().sort_values("Category")Use a dictionary to create a dataframe for each month. Each monthly dataframe is sorted by the full order timestamp.
monthly_data = {}
for month in range(1, 13):
monthly_data[month] = (
data[data["Month"] == month]
.sort_values("Order Date")
.reset_index(drop=True)
)
# Access a month, for example:
april_data = monthly_data[4]
december_data = monthly_data[12]
# Check each monthly dataframe:
for month, month_df in monthly_data.items():
print(month, month_df.shape)Order Date.dt.to_period("M") instead.data["Sales"] = data["Quantity Ordered"] * data["Price Each"] data[["Product", "Quantity Ordered", "Price Each", "Sales"]].head()
We now use the cleaned and transformed data to answer the 17 questions from the original project brief.
Group the sales amount by month and compare the totals. December is the strongest month in this dataset.
monthly_sales = data.groupby("Month")["Sales"].sum()
best_month = monthly_sales.idxmax()
best_sales = monthly_sales.max()
print(best_month, best_sales)
monthly_sales.plot(kind="bar", color="steelblue")
plt.title("Total Sales by Month")
plt.xlabel("Month")
plt.ylabel("Sales ($)")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()Interpretation: December generates the highest revenue, followed by October. This may be connected to holiday shopping and seasonal demand, but the dataset does not contain campaign or holiday information to prove the cause.
First decide what “sold the most” means. We compare both total sales value and total units, rather than confusing record count with revenue.
city_sales = data.groupby("City")["Sales"].sum().sort_values(ascending=False)
city_units = data.groupby("City")["Quantity Ordered"].sum().sort_values(ascending=False)
print(city_sales)
print(city_units)
city_sales.plot(kind="bar", title="Revenue by City")
plt.ylabel("Sales ($)")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()San Francisco leads both measures: approximately $8,254,743.55 in sales and 50,239 units.
Count the product-line records by hour. This gives a useful first estimate of when shopping activity is highest.
data["Hour"] = data["Order Date"].dt.hour
hourly_activity = data.groupby("Hour").size()
hourly_activity.plot(kind="line", marker="o")
plt.title("Number of Product Records by Hour")
plt.xlabel("Hour of Day")
plt.ylabel("Number of Records")
plt.xticks(range(0, 24))
plt.grid()
plt.tight_layout()
plt.show()The busiest hour is 7 PM (19:00), with 12,886 product records. Noon is the next major peak, with 12,573 records.
Recommendation: test advertisements around 11 AM–1 PM and 6 PM–9 PM. The strongest single hour is 7 PM. This is a timing hypothesis, not proof of ad effectiveness: the dataset records purchases, not ad views, clicks or campaign costs.
Compare total units within each category. The least-sold items in the cleaned data are:
least_sold = (
data.groupby(["Category", "Product"])["Quantity Ordered"]
.sum()
.reset_index()
.sort_values("Quantity Ordered")
.groupby("Category")
.first()
)
print(least_sold)| Category | Least-sold product | Units |
|---|---|---|
| Accessories | Lightning Charging Cable | 23169 |
| Headphones | Bose SoundSport Headphones | 13430 |
| Home Appliances & TVs | LG Dryer | 646 |
| Laptops | ThinkPad Laptop | 4128 |
| Monitors | 20in Monitor | 4126 |
| Phones | Vareebadd Phone | 2068 |
Low sales can have several possible causes: a higher price, a smaller target audience, fewer product features, limited stock, a newer product or competition from alternatives. The dataset alone cannot identify which cause is correct. For example, a low-volume laptop may be expensive and aimed at a smaller group, but we would need stock, marketing and customer data to test that idea.
The original project asks for seasonal patterns. The dataset does not define seasons, so we use a simple Northern Hemisphere calendar grouping: Winter = Dec–Feb, Summer = Mar–May, Rainy = Jun–Aug, and Autumn = Sep–Nov. This is an analysis assumption, not a weather measurement.
season_map = {
12: "Winter", 1: "Winter", 2: "Winter",
3: "Summer", 4: "Summer", 5: "Summer",
6: "Rainy", 7: "Rainy", 8: "Rainy",
9: "Autumn", 10: "Autumn", 11: "Autumn"
}
data["Season"] = data["Month"].map(season_map)
season_product = (
data.groupby(["Season", "Product"])["Quantity Ordered"]
.sum()
.reset_index()
)
season_product.sort_values(
["Season", "Quantity Ordered"], ascending=[True, False]
).groupby("Season").head(5)| Season | Highest-volume product | Units |
|---|---|---|
| Winter | AAA Batteries (4-pack) | 7,809 |
| Summer | AAA Batteries (4-pack) | 8,336 |
| Rainy | AAA Batteries (4-pack) | 6,541 |
| Autumn | AAA Batteries (4-pack) | 8,300 |
AAA Batteries (4-pack) leads unit volume in each of these seasonal groups. This suggests steady demand for everyday accessories. It does not prove batteries are season-specific. To explain seasonal causes, we would need more years of data and information about promotions, weather, holidays and product availability.
march_phones = data[
(data["Month"] == 3) & (data["Category"] == "Phones")
]
march_phone_units = (
march_phones.groupby("Product")["Quantity Ordered"]
.sum()
.sort_values(ascending=False)
)
print(march_phone_units)headphone_prices = (
data[data["Category"] == "Headphones"]
.groupby("Product")["Price Each"]
.mean()
.sort_values(ascending=False)
)
print(headphone_prices)| Headphone | Average unit price |
|---|---|
| Apple Airpods Headphones | $150.00 |
| Bose SoundSport Headphones | $99.99 |
| Wired Headphones | $11.99 |
Apple Airpods Headphones are the most expensive of the three headphone products in the file.
Compare the minimum and maximum observed unit price for each product. Do not confuse different products' prices with price changes for the same product.
price_check = data.groupby("Product")["Price Each"].agg(
min_price="min",
max_price="max",
unique_prices="nunique"
)
price_changes = price_check[price_check["unique_prices"] > 1]
print(price_changes)If genuine price changes were present, possible reasons could include discounts, promotions, price updates, regional pricing or data-entry errors. We cannot claim any of these occurred here.
Use the two wireless headphone models (Apple Airpods and Bose SoundSport) and compare their combined units with Wired Headphones.
wireless_units = data[
data["Product"].isin([
"Apple Airpods Headphones",
"Bose SoundSport Headphones"
])
]["Quantity Ordered"].sum()
wired_units = data.loc[
data["Product"] == "Wired Headphones",
"Quantity Ordered"
].sum()
print("Wireless:", wireless_units)
print("Wired:", wired_units)Wireless models together sell more units in this dataset. This is a comparison of the listed products, not a complete survey of every wired and wireless earphone brand.
“Bulk” needs a clear definition. Here we measure the share of product-line records where the quantity is greater than one. This is a useful proxy, but it is not the same as a wholesale order.
bulk_summary = data.groupby(["Category", "Product"]).agg(
total_units=("Quantity Ordered", "sum"),
order_lines=("Order ID", "size"),
multi_unit_lines=("Quantity Ordered", lambda x: (x > 1).sum()),
average_units_per_line=("Quantity Ordered", "mean")
)
bulk_summary["multi_unit_share"] = (
bulk_summary["multi_unit_lines"] / bulk_summary["order_lines"]
)
bulk_summary.sort_values(
["Category", "multi_unit_share"],
ascending=[True, False]
).groupby(level=0).head(1)| Category | Product with highest multi-unit share | Total units | Multi-unit lines | Average units / line |
|---|---|---|---|---|
| Accessories | AAA Batteries (4-pack) | 30986 | 33.54% | 1.503 |
| Headphones | Wired Headphones | 20524 | 8.07% | 1.089 |
| Home Appliances & TVs | Flatscreen TV | 4813 | 0.40% | 1.004 |
| Laptops | Macbook Pro Laptop | 4725 | 0.08% | 1.001 |
| Monitors | 20in Monitor | 4126 | 0.68% | 1.007 |
| Phones | Vareebadd Phone | 2068 | 0.15% | 1.001 |
AAA Batteries (4-pack) stands out in Accessories. Its relatively low unit price and the fact that batteries are often needed in multiples may help explain the pattern, but this is a possible explanation rather than a proven cause. In the other categories, the top products have much smaller multi-unit shares.
December leads revenue with $4.61 million.
San Francisco leads revenue and unit volume.
7 PM has the highest number of product records.
MacBook Pro Laptop generates the highest total sales value.
iPhone leads with 538 units.
Wireless models combined outsell the wired model listed.
data.to_csv("sales_cleaned.csv", index=False)
print("Cleaned dataset saved successfully.")© 2021 edSlash. All Rights Reserved.