Exploratory Data Analysis on Sales Data in Python

Analyse the given dataset completely and perform the following questions.

  1. Convert the text based categorical columns to numeric columns
  2. Convert the Order Date column into Day, Month, Year and Time columns separately
  3. Create a new column and store the Price data as rounded off in integer format
  4. Create a new column and store the PIN Codes from the Address column
  5. Create a new column named City and store the city names from the Address column
  6. Group Product column into different categories such as Phones, Accessories, etc according to the data available.
  7. Create 12 separate date ordered dataframes for every
  8. What was the best month for sales? How much was earned that month? Explain via graph/chart
  9. What city sold the most product?
  10. What time should we display advertisements to maximize likelihood of customer’s buying product?
  11. Which product was sold the least as per your categories and what might be the reason behind that. Explain your analysis.
  12. Which product is most likely to be sold more during winter season, summer season and rainy season? Explain the possible reason behind the High-Volume Sale
  13. Which phone is sold most during the month of March?
  14. Which headphones are the most expensive?
  15. Check if the price of any product is changing in different If yes, explain the possible reason behind the price change.
  16. People prefer which product more in earphones, wired or wireless?
  17. Which product in every category in more likely to be ordered in bulk?

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.

Jupyter / Google ColabPandas & NumPyMatplotlib & SeabornReal-world CSV
Project goal: turn raw transaction records into reliable answers about products, sales, cities, dates, customer buying times and purchasing patterns.

Introduction

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.

Original columns

  • Order ID: order identifier.
  • Product: item sold.
  • Quantity Ordered: units in that product line.
  • Price Each: price of one unit, in US dollars.
  • Order Date: date and time in month/day/year format.
  • Purchase Address: delivery address.

What EDA means

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.

Source and method note: The PDF supplied is a very long, single-page screenshot of a notebook. The page text includes 17 project questions and sections on loading, cleaning, transforming and analysing the sales data. This HTML keeps that task list and notebook approach, but replaces fragile manual row-index deletion with reproducible cleaning steps and re-checks the results against the supplied CSV.

Load the libraries

Sales_EDA.ipynb · Code cellIn [1]
In [1]
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)
Out [1]
Libraries imported.

Pandas handles tables; NumPy supports numerical work; Matplotlib and Seaborn create charts.

Read the CSV file

Load the datasetIn [2]
In [2]
# Put SalesAnalysis.csv in the same folder as this notebook.
df = pd.read_csv("SalesAnalysis.csv")
df.head()
Out [2]
Order IDProductQuantity OrderedPrice EachOrder DatePurchase Address
176558USB-C Charging Cable211.9504/19/19 08:46917 1st St, Dallas, TX 75001
176559Bose SoundSport Headphones199.9904/07/19 22:30682 Chestnut St, Boston, MA 02215
176560Google Phone160004/12/19 14:38669 Spruce St, Los Angeles, CA 90001

Data cleaning

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.

Inspect the data types

Check column typesIn [3]
In [3]
df.dtypes
df.info()
Out [3]

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.

Find repeated header rows

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.

Find the repeated header rowsIn [4]
In [4]
df["Product"].value_counts().head(20)
df[df["Quantity Ordered"] == "Quantity Ordered"].head()
Out [4]

355 repeated header records are present. The correct fix is to filter them using a condition, rather than hard-coding hundreds of row indexes.

Remove blank rows and repeated headers

Clean invalid rowsIn [5]
In [5]
# 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)
Out [5]

After removing 545 blank rows, 355 repeated headers and records with invalid required values, 185,950 valid rows remain before duplicate checking.

Check missing values and duplicates

Missing-value and duplicate checksIn [6]
In [6]
data.isna().sum()
data.duplicated().sum()

# Remove exact duplicate rows only.
data = data.drop_duplicates().copy()

data.shape
Out [6]

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.

Final cleaned data: 185,686 product-line records. All six required source fields are present, dates are parsed, quantity and price are numeric, and exact duplicate rows are removed.

Transforming the data

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.

Task 1Convert categorical text to numeric values where appropriate

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.

Numeric columns and optional encodingCode cell
In [7]
# 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.

Task 2Split Order Date into Day, Month, Year and Time

Extract date and time partsCode cell
In [8]
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()

Task 3Create a rounded price column

Keep the original price for accurate revenue calculations. Create a separate rounded column only for display or grouping.

Round unit priceCode cell
In [9]
data["Price Rounded"] = data["Price Each"].round().astype("int64")
data[["Price Each", "Price Rounded"]].head()

Task 4Extract PIN codes from the address

Extract ZIP / PIN codeCode cell
In [10]
# 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()

Task 5Create a City column

Extract city nameCode cell
In [11]
data["City"] = (
    data["Purchase Address"]
    .str.split(",")
    .str[1]
    .str.strip()
)
data[["Purchase Address", "City"]].head()

Task 6Group products into categories

We create broad groups to compare similar products. This grouping is a practical choice for this dataset, not a universal product taxonomy.

Create product categoriesCode cell
In [12]
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")

Task 7Create 12 separate monthly dataframes in date order

Use a dictionary to create a dataframe for each month. Each monthly dataframe is sorted by the full order timestamp.

Create monthly datasetsCode cell
In [13]
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)
The source data spans 2019 and includes some records dated January 2020. The code above groups by month number, so January combines January 2019 and January 2020. If you need separate calendar months across years, group by Order Date.dt.to_period("M") instead.

Create the sales amount

Calculate revenue per product lineCode cell
In [14]
data["Sales"] = data["Quantity Ordered"] * data["Price Each"]

data[["Product", "Quantity Ordered", "Price Each", "Sales"]].head()

Answering the project questions

We now use the cleaned and transformed data to answer the 17 questions from the original project brief.

Task 8What was the best month for sales? How much was earned?

Group the sales amount by month and compare the totals. December is the strongest month in this dataset.

Monthly revenueCode cell
In [15]
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()
Out [15]
December — $4,608,295.70
Jan
$1.82M
Feb
$2.20M
Mar
$2.80M
Apr
$3.39M
May
$3.15M
Jun
$2.58M
Jul
$2.65M
Aug
$2.24M
Sep
$2.09M
Oct
$3.73M
Nov
$3.20M
Dec
$4.61M

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.

Task 9Which city sold the most product?

First decide what “sold the most” means. We compare both total sales value and total units, rather than confusing record count with revenue.

Sales by cityCode cell
In [16]
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()
Out [16]

San Francisco leads both measures: approximately $8,254,743.55 in sales and 50,239 units.

San Francisco
$8.25M
Los Angeles
$5.45M
New York City
$4.66M
Boston
$3.66M
Atlanta
$2.79M
Dallas
$2.77M
Seattle
$2.75M
Portland
$2.32M
Austin
$1.82M

Task 10What time should advertisements be displayed?

Count the product-line records by hour. This gives a useful first estimate of when shopping activity is highest.

Purchases by hourCode cell
In [17]
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()
Out [17]

The busiest hour is 7 PM (19:00), with 12,886 product records. Noon is the next major peak, with 12,573 records.

19:00
12,886
12:00
12,573
11:00
12,392
18:00
12,263
20:00
12,218
13:00
12,115
14:00
10,965
10:00
10,929

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.

Task 11Which product sold the least in each category, and why?

Compare total units within each category. The least-sold items in the cleaned data are:

Least-sold product by categoryCode cell
In [18]
least_sold = (
    data.groupby(["Category", "Product"])["Quantity Ordered"]
    .sum()
    .reset_index()
    .sort_values("Quantity Ordered")
    .groupby("Category")
    .first()
)
print(least_sold)
Out [18]
CategoryLeast-sold productUnits
AccessoriesLightning Charging Cable23169
HeadphonesBose SoundSport Headphones13430
Home Appliances & TVsLG Dryer646
LaptopsThinkPad Laptop4128
Monitors20in Monitor4126
PhonesVareebadd Phone2068

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.

Task 12Which products sell more in winter, summer and rainy seasons?

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.

Assign seasons and compare product unitsCode cell
In [19]
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)
Out [19]
SeasonHighest-volume productUnits
WinterAAA Batteries (4-pack)7,809
SummerAAA Batteries (4-pack)8,336
RainyAAA Batteries (4-pack)6,541
AutumnAAA 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.

Task 13Which phone sold the most in March?

March phone salesCode cell
In [20]
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)
Out [20]
iPhone leads March phone sales with 538 units, followed by Google Phone (463) and Vareebadd Phone (174).

Task 14Which headphones are the most expensive?

Compare headphone pricesCode cell
In [21]
headphone_prices = (
    data[data["Category"] == "Headphones"]
    .groupby("Product")["Price Each"]
    .mean()
    .sort_values(ascending=False)
)
print(headphone_prices)
Out [21]
HeadphoneAverage 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.

Task 15Does the price of any product change over time?

Compare the minimum and maximum observed unit price for each product. Do not confuse different products' prices with price changes for the same product.

Check price variation by productCode cell
In [22]
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)
Out [22]
No product shows a changing unit price in the cleaned dataset: each product has one consistent price value. Some values that look different in the raw CSV are malformed repeated-header or invalid rows and should not be treated as real 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.

Task 16Do customers prefer wired or wireless headphones?

Use the two wireless headphone models (Apple Airpods and Bose SoundSport) and compare their combined units with Wired Headphones.

Wired versus wireless unitsCode cell
In [23]
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)
Out [23]
Wireless: 29,067 units
Wired: 20,524 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.

Task 17Which product in each category is most likely to be ordered in bulk?

“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.

Find products with multiple units per lineCode cell
In [24]
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)
Out [24]
CategoryProduct with highest multi-unit shareTotal unitsMulti-unit linesAverage units / line
AccessoriesAAA Batteries (4-pack)3098633.54%1.503
HeadphonesWired Headphones205248.07%1.089
Home Appliances & TVsFlatscreen TV48130.40%1.004
LaptopsMacbook Pro Laptop47250.08%1.001
Monitors20in Monitor41260.68%1.007
PhonesVareebadd Phone20680.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.

Conclusion and key findings

Strongest month

December leads revenue with $4.61 million.

Leading city

San Francisco leads revenue and unit volume.

Peak buying hour

7 PM has the highest number of product records.

Top sales-value product

MacBook Pro Laptop generates the highest total sales value.

March phone leader

iPhone leads with 538 units.

Headphone comparison

Wireless models combined outsell the wired model listed.

Save the cleaned dataset

Export the cleaned dataCode cell
In [25]
data.to_csv("sales_cleaned.csv", index=False)
print("Cleaned dataset saved successfully.")

What we should remember

  • Always inspect the raw data before analysis.
  • Remove invalid records using repeatable rules, not long lists of fixed row numbers.
  • Keep identifiers and category labels separate from measured numeric values.
  • Use the original price to calculate sales; rounded prices are for display only.
  • Explain whether a result means revenue, units, rows, or unique orders.
  • Do not claim a cause from a chart unless the dataset contains evidence for that cause.
  • Check assumptions such as seasonal definitions and category grouping.
Final takeaway: EDA turns a spreadsheet into a story about what is happening in a business. The strongest analysis does more than show a chart: it explains the result, its limits, and what the business could investigate next.