Pandas E-commerce Data Analysis in Practice
This section uses a complete e-commerce data analysis case to comprehensively apply Pandas' various features for data analysis.
Case overview
Analyze order data from an e-commerce platform, covering dimensions such as sales trends, product performance, and customer analysis.
Data preparation
Example
import
pandas
as
pd
import
numpy
as
np
Simulate e-commerce order data
np.
random
.
seed
(
42
)
n_orders
=
1000
orders
=
pd.
DataFrame
(
{
"order_id"
:
range
(
1
,
n_orders +
1
)
,
"Customer ID"
: np.
random
.
randint
(
100
,
200
,
n_orders
)
,
"product_id"
: np.
random
.
randint
(
1
,
20
,
n_orders
)
,
"order_date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
n_orders
,
freq
=
"30min"
)
,
"quantity"
: np.
random
.
randint
(
1
,
5
,
n_orders
)
,
"unit_price"
: np.
random
.
uniform
(
10
,
500
,
n_orders
)
.
round
(
2
)
}
)
Calculate the order amount
orders
[
"order_amount"
]
=
(
orders
[
"quantity"
]
- orders
[
"unit_price"
]
)
.
round
(
2
)
(
"Order data overview:"
)
(
orders.
head
(
10
)
)
(
f
"\nData volume: {len(orders)} records"
)
Data preprocessing
Example
Extract date features
orders
[
"date"
]
=
orders
[
"order_date"
]
.
dt
.
date
orders
[
"hours"
]
=
orders
[
"order_date"
]
.
dt
.
hour
orders
[
Week
]
=
orders
[
"order_date"
]
.
dt
.
day_name
(
)
orders
[
"Month"
]
=
orders
[
"order_date"
]
.
dt
.
month
(
"After adding time features:"
)
(
orders.
head
(
)
)
(
)
Check for missing values
(
"Missing value check:"
)
(
orders.
isnull
(
)
.
sum
(
)
)
Sales analysis
Overall sales situation
Example
Overall sales metrics
(
"=== Overall sales ===\n"
)
(
f
"Total orders: {len(orders):,}"
)
(
f
"Total sales: CNY {orders['order_amount'].sum():,.2f}"
)
(
f
"Average order amount: CNY {orders['order_amount'].mean():,.2f}"
)
(
f
"Median order amount: CNY {orders['order_amount'].median():,.2f}"
)
(
)
Statistics by month
monthly
=
orders.
groupby
(
"Month"
)
.
agg
(
{
"order_id"
:
"count"
,
"order_amount"
:
"sum"
,
"Customer ID"
:
"nunique"
}
)
.
rename
(
columns
=
{
"order_id"
:
"order_count"
,
"order_amount"
:
"Sales"
,
"Customer ID"
:
"customer_count"
}
)
(
"Monthly sales trend:"
)
(
monthly
)
Product analysis
Example
Product sales ranking
product_sales
=
orders.
groupby
(
"product_id"
)
.
agg
(
{
"order_id"
:
"count"
,
"quantity"
:
"sum"
,
"order_amount"
:
"sum"
}
)
.
rename
(
columns
=
{
"order_id"
:
"order_count"
,
"quantity"
:
"Sales"
,
"order_amount"
:
"Sales"
}
)
.
sort_values
(
"Sales"
,
ascending
=
False
)
(
"=== Product sales ranking Top 10 ===\n"
)
(
product_sales.
head
(
10
)
)
(
)
Best-selling products
(
f
"Best-selling product: product {product_sales.index[0]}"
)
(
f
"Sales amount: CNY {product_sales.iloc[0]['sales_amount']:,.2f}"
)
Customer analysis
Example
Customer spending analysis
customer_sales
=
orders.
groupby
(
"Customer ID"
)
.
agg
(
{
"order_id"
:
"count"
,
"order_amount"
:
"sum"
}
)
.
rename
(
columns
=
{
"order_id"
:
"order_count"
,
"order_amount"
:
"total_spending"
}
)
(
"=== Customer analysis ===\n"
)
(
f
"Number of active customers: {len(customer_sales)}"
)
(
f
"Average orders per customer: {customer_sales['order_count'].mean():.1f}"
)
(
f
"Average spending per customer: CNY {customer_sales['total_spending'].mean():,.2f}"
)
(
)
Customer segmentation
customer_sales
[
"segment"
]
=
pd.
cut
(
customer_sales
[
"total_spending"
]
,
bins
=
[
0
,
1000
,
5000
,
10000
,
float
(
"inf"
)
]
,
labels
=
[
"Regular"
,
"Silver"
,
"Gold"
,
"VIP"
]
)
(
"Customer segmentation statistics:"
)
(
customer_sales
[
"segment"
]
.
value_counts
(
)
)
Time analysis
Example
Analysis by time period
hourly
=
orders.
groupby
(
"hours"
)
[
"order_amount"
]
.
sum
(
)
(
"=== Sales analysis by time period ===\n"
)
(
f
"Peak sales hour: {hourly.idxmax()} o'clock"
)
(
f
"Sales amount in that period: CNY {hourly.max():,.2f}"
)
(
)
Analysis by day of week
weekday
=
orders.
groupby
(
Week
)
[
"order_amount"
]
.
sum
(
)
.
reindex
(
[
"Monday"
,
"Tuesday"
,
"Wednesday"
,
"Thursday"
,
"Friday"
,
"Saturday"
,
"Sunday"
]
)
(
"Sales by day of week:"
)
for
day
,
amount
in
weekday.
items
(
)
:
(
f
"{day}: ¥{amount:,.2f}"
)
Analysis summary
Example
(
"""
=== E-commerce Data Analysis Summary ===
-
Sales overview
- Total orders: {0}
- Total sales: CNY {1:,.2f}
- Average order value: CNY {2:.2f} -
Product performance
- Best-selling product: product {3}
- Product sales are unevenly distributed, with top products contributing a large share of revenue -
Customer insights
- Active customers: {4} people
- It is recommended to focus on retaining high-value customers -
Time patterns
- Sales peak around {5} o'clock
- Marketing strategies can be adjusted according to peak periods -
Optimization Suggestions
- 1) Increase inventory and promotion for best-selling products
- 2) Provide personalized service to high-value customers
- 3) Increase customer service staffing during peak sales hours
"""
.
format
(
len
(
orders
)
,
orders
[
"order_amount"
]
.
sum
(
)
,
orders
[
"order_amount"
]
.
mean
(
)
,
product_sales.
index
[
0
]
,
len
(
customer_sales
)
,
hourly.
idxmax
(
)
)
)