Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas E-commerce Data Analysis in Practice

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"

]

[

"unit_price"

]

)

.

round

(

2

)

print

(

"Order data overview:"

)

print

(

orders.

head

(

10

)

)

print

(

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

print

(

"After adding time features:"

)

print

(

orders.

head

(

)

)

print

(

)

Check for missing values

print

(

"Missing value check:"

)

print

(

orders.

isnull

(

)

.

sum

(

)

)


Sales analysis

Overall sales situation

Example

Overall sales metrics

print

(

"=== Overall sales ===\n"

)

print

(

f

"Total orders: {len(orders):,}"

)

print

(

f

"Total sales: CNY {orders['order_amount'].sum():,.2f}"

)

print

(

f

"Average order amount: CNY {orders['order_amount'].mean():,.2f}"

)

print

(

f

"Median order amount: CNY {orders['order_amount'].median():,.2f}"

)

print

(

)

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"

}

)

print

(

"Monthly sales trend:"

)

print

(

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

)

print

(

"=== Product sales ranking Top 10 ===\n"

)

print

(

product_sales.

head

(

10

)

)

print

(

)

Best-selling products

print

(

f

"Best-selling product: product {product_sales.index[0]}"

)

print

(

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"

}

)

print

(

"=== Customer analysis ===\n"

)

print

(

f

"Number of active customers: {len(customer_sales)}"

)

print

(

f

"Average orders per customer: {customer_sales['order_count'].mean():.1f}"

)

print

(

f

"Average spending per customer: CNY {customer_sales['total_spending'].mean():,.2f}"

)

print

(

)

Customer segmentation

customer_sales

[

"segment"

]

=

pd.

cut

(

    customer_sales

[

"total_spending"

]

,

    bins

=

[

0

,

1000

,

5000

,

10000

,

float

(

"inf"

)

]

,

    labels

=

[

"Regular"

,

"Silver"

,

"Gold"

,

"VIP"

]

)

print

(

"Customer segmentation statistics:"

)

print

(

customer_sales

[

"segment"

]

.

value_counts

(

)

)

Time analysis

Example

Analysis by time period

hourly

=

orders.

groupby

(

"hours"

)

[

"order_amount"

]

.

sum

(

)

print

(

"=== Sales analysis by time period ===\n"

)

print

(

f

"Peak sales hour: {hourly.idxmax()} o'clock"

)

print

(

f

"Sales amount in that period: CNY {hourly.max():,.2f}"

)

print

(

)

Analysis by day of week

weekday

=

orders.

groupby

(

Week

)

[

"order_amount"

]

.

sum

(

)

.

reindex

(

[

   

"Monday"

,

"Tuesday"

,

"Wednesday"

,

"Thursday"

,

"Friday"

,

"Saturday"

,

"Sunday"

]

)

print

(

"Sales by day of week:"

)

for

day

,

amount

in

weekday.

items

(

)

:

   

print

(

f

"{day}: ¥{amount:,.2f}"

)


Analysis summary

Example

print

(

"""
=== E-commerce Data Analysis Summary ===

  1. Sales overview
       - Total orders: {0}
       - Total sales: CNY {1:,.2f}
       - Average order value: CNY {2:.2f}

  2. Product performance
       - Best-selling product: product {3}
       - Product sales are unevenly distributed, with top products contributing a large share of revenue

  3. Customer insights
       - Active customers: {4} people
       - It is recommended to focus on retaining high-value customers

  4. Time patterns
       - Sales peak around {5} o'clock
       - Marketing strategies can be adjusted according to peak periods

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

(

)

)

)