Python項目實戰(zhàn):電商平臺銷售數(shù)據(jù)分析
前言
最近在學(xué)習(xí) Rust 的同時,我也在鞏固 Python 的數(shù)據(jù)分析技能。作為一個從后端轉(zhuǎn) Rust 的萌新,我認為數(shù)據(jù)分析是一項非常重要的技能,無論是在后端開發(fā)還是其他領(lǐng)域,都能發(fā)揮重要作用。
今天,我就來分享一個 Python 數(shù)據(jù)分析的實戰(zhàn)項目,希望能幫到和我一樣的萌新們。
項目背景
我們將分析一個電商平臺的銷售數(shù)據(jù),了解銷售趨勢、用戶行為和產(chǎn)品表現(xiàn),為業(yè)務(wù)決策提供數(shù)據(jù)支持。
數(shù)據(jù)準備
首先,我們需要準備數(shù)據(jù)。這里我們使用一個模擬的電商銷售數(shù)據(jù)集,包含以下字段:
order_id:訂單IDcustomer_id:客戶IDorder_date:訂單日期product_id:產(chǎn)品IDproduct_name:產(chǎn)品名稱category:產(chǎn)品類別price:產(chǎn)品價格quantity:購買數(shù)量total_amount:訂單總金額payment_method:支付方式shipping_address:收貨地址
環(huán)境搭建
我們需要安裝以下庫:
pandas:用于數(shù)據(jù)處理和分析numpy:用于數(shù)值計算matplotlib:用于數(shù)據(jù)可視化seaborn:用于高級數(shù)據(jù)可視化jupyter:用于交互式數(shù)據(jù)分析
可以使用以下命令安裝:
pip install pandas numpy matplotlib seaborn jupyter
數(shù)據(jù)分析流程
1. 數(shù)據(jù)加載和預(yù)處理
首先,我們需要加載數(shù)據(jù)并進行預(yù)處理:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 設(shè)置中文字體
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負號
# 加載數(shù)據(jù)
df = pd.read_csv('sales_data.csv')
# 查看數(shù)據(jù)基本信息
print(df.info())
# 查看數(shù)據(jù)前幾行
print(df.head())
# 檢查缺失值
print(df.isnull().sum())
# 處理缺失值
df = df.dropna()
# 轉(zhuǎn)換數(shù)據(jù)類型
df['order_date'] = pd.to_datetime(df['order_date'])
# 添加新列
df['year'] = df['order_date'].dt.year
df['month'] = df['order_date'].dt.month
df['day'] = df['order_date'].dt.day
2. 數(shù)據(jù)探索性分析
接下來,我們進行數(shù)據(jù)探索性分析,了解數(shù)據(jù)的基本特征:
# 統(tǒng)計描述
print(df.describe())
# 銷售趨勢分析
sales_by_date = df.groupby('order_date')['total_amount'].sum()
plt.figure(figsize=(12, 6))
sales_by_date.plot()
plt.title('每日銷售趨勢')
plt.xlabel('日期')
plt.ylabel('銷售額')
plt.show()
# 月度銷售趨勢
sales_by_month = df.groupby(['year', 'month'])['total_amount'].sum().reset_index()
sales_by_month['date'] = pd.to_datetime(sales_by_month[['year', 'month']].assign(day=1))
plt.figure(figsize=(12, 6))
sns.lineplot(x='date', y='total_amount', data=sales_by_month)
plt.title('月度銷售趨勢')
plt.xlabel('日期')
plt.ylabel('銷售額')
plt.show()
# 產(chǎn)品類別銷售分析
sales_by_category = df.groupby('category')['total_amount'].sum().sort_values(ascending=False)
plt.figure(figsize=(12, 6))
sales_by_category.plot(kind='bar')
plt.title('各產(chǎn)品類別銷售額')
plt.xlabel('產(chǎn)品類別')
plt.ylabel('銷售額')
plt.xticks(rotation=45)
plt.show()
# 產(chǎn)品銷售分析
top_10_products = df.groupby('product_name')['total_amount'].sum().sort_values(ascending=False).head(10)
plt.figure(figsize=(12, 6))
top_10_products.plot(kind='bar')
plt.title('銷售額前10的產(chǎn)品')
plt.xlabel('產(chǎn)品名稱')
plt.ylabel('銷售額')
plt.xticks(rotation=45)
plt.show()
# 支付方式分析
payment_method_count = df.groupby('payment_method')['order_id'].count()
plt.figure(figsize=(10, 6))
plt.pie(payment_method_count, labels=payment_method_count.index, autopct='%1.1f%%')
plt.title('支付方式分布')
plt.show()
# 客戶購買行為分析
customer_purchase = df.groupby('customer_id')['total_amount'].agg(['count', 'sum', 'mean']).rename(columns={'count': '購買次數(shù)', 'sum': '總消費', 'mean': '平均消費'})
plt.figure(figsize=(12, 6))
sns.histplot(customer_purchase['購買次數(shù)'], bins=20)
plt.title('客戶購買次數(shù)分布')
plt.xlabel('購買次數(shù)')
plt.ylabel('客戶數(shù)')
plt.show()
plt.figure(figsize=(12, 6))
sns.histplot(customer_purchase['總消費'], bins=20)
plt.title('客戶總消費分布')
plt.xlabel('總消費')
plt.ylabel('客戶數(shù)')
plt.show()
3. 數(shù)據(jù)深度分析
現(xiàn)在,我們進行更深入的分析,發(fā)現(xiàn)數(shù)據(jù)中的模式和規(guī)律:
# 客戶價值分析
# 計算客戶生命周期價值 (CLV)
# 這里簡化計算,使用總消費作為CLV
customer_clv = df.groupby('customer_id')['total_amount'].sum().sort_values(ascending=False)
# 客戶分層
top_20_percent = int(len(customer_clv) * 0.2)
top_customers = customer_clv.head(top_20_percent)
print(f"前20%客戶數(shù)量: {top_20_percent}")
print(f"前20%客戶消費占比: {top_customers.sum() / customer_clv.sum():.2f}")
# 產(chǎn)品關(guān)聯(lián)分析
# 計算產(chǎn)品之間的關(guān)聯(lián)度
from itertools import combinations
from collections import defaultdict
# 構(gòu)建購物籃
baskets = df.groupby('order_id')['product_name'].apply(list).tolist()
# 計算產(chǎn)品對的出現(xiàn)次數(shù)
product_pairs = defaultdict(int)
for basket in baskets:
if len(basket) >= 2:
for pair in combinations(set(basket), 2):
product_pairs[tuple(sorted(pair))] += 1
# 轉(zhuǎn)換為DataFrame
product_pairs_df = pd.DataFrame.from_dict(product_pairs, orient='index', columns=['count']).reset_index()
product_pairs_df[['product1', 'product2']] = pd.DataFrame(product_pairs_df['index'].tolist(), index=product_pairs_df.index)
product_pairs_df = product_pairs_df.drop('index', axis=1)
product_pairs_df = product_pairs_df.sort_values('count', ascending=False)
print("產(chǎn)品關(guān)聯(lián)度前10:")
print(product_pairs_df.head(10))
# 銷售預(yù)測
# 使用移動平均法進行銷售預(yù)測
from statsmodels.tsa.holtwinters import SimpleExpSmoothing
# 準備數(shù)據(jù)
sales_series = sales_by_date
# 擬合模型
model = SimpleExpSmoothing(sales_series).fit(smoothing_level=0.6, optimized=False)
# 預(yù)測未來7天
forecast = model.forecast(7)
# 可視化預(yù)測結(jié)果
plt.figure(figsize=(12, 6))
plt.plot(sales_series.index, sales_series.values, label='實際銷售額')
plt.plot(forecast.index, forecast.values, label='預(yù)測銷售額', linestyle='--')
plt.title('銷售額預(yù)測')
plt.xlabel('日期')
plt.ylabel('銷售額')
plt.legend()
plt.show()
4. 數(shù)據(jù)可視化和報告
最后,我們將分析結(jié)果進行可視化,并生成一份分析報告:
# 生成綜合分析報告
import io
from PIL import Image
# 創(chuàng)建一個HTML報告
report_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>電商銷售數(shù)據(jù)分析報告</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1 { color: #333; }
h2 { color: #555; }
.section { margin-bottom: 30px; }
.chart { margin: 20px 0; }
table { border-collapse: collapse; width: 100%; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>電商銷售數(shù)據(jù)分析報告</h1>
<div class="section">
<h2>1. 數(shù)據(jù)概覽</h2>
<p>本次分析基于電商平臺的銷售數(shù)據(jù),包含訂單信息、客戶信息、產(chǎn)品信息等。</p>
<p>數(shù)據(jù)量:{total_orders} 條訂單記錄</p>
<p>時間范圍:{start_date} 至 {end_date}</p>
<p>總銷售額:¥{total_sales:.2f}</p>
<p>客戶數(shù)量:{total_customers} 位</p>
<p>產(chǎn)品種類:{total_products} 種</p>
</div>
<div class="section">
<h2>2. 銷售趨勢分析</h2>
<p>從銷售趨勢圖可以看出,銷售額呈現(xiàn)[上升/下降/穩(wěn)定]趨勢。</p>
<div class="chart">
<img src="data:image/png;base64,{sales_trend_chart}" alt="銷售趨勢圖">
</div>
</div>
<div class="section">
<h2>3. 產(chǎn)品分析</h2>
<p>銷售額最高的產(chǎn)品類別是 {top_category},占總銷售額的 {top_category_percent:.2f}%。</p>
<p>銷售額最高的產(chǎn)品是 {top_product},銷售額為 ¥{top_product_sales:.2f}。</p>
<div class="chart">
<img src="data:image/png;base64,{category_chart}" alt="產(chǎn)品類別銷售圖">
</div>
<div class="chart">
<img src="data:image/png;base64,{product_chart}" alt="產(chǎn)品銷售圖">
</div>
</div>
<div class="section">
<h2>4. 客戶分析</h2>
<p>前20%的客戶貢獻了 {top_customer_percent:.2f}% 的銷售額,體現(xiàn)了帕累托法則(80/20法則)。</p>
<div class="chart">
<img src="data:image/png;base64,{customer_chart}" alt="客戶消費分布圖">
</div>
</div>
<div class="section">
<h2>5. 支付方式分析</h2>
<p>最常用的支付方式是 {top_payment_method},占比 {top_payment_percent:.2f}%。</p>
<div class="chart">
<img src="data:image/png;base64,{payment_chart}" alt="支付方式分布圖">
</div>
</div>
<div class="section">
<h2>6. 產(chǎn)品關(guān)聯(lián)分析</h2>
<p>最常一起購買的產(chǎn)品組合是:</p>
<table>
<tr>
<th>產(chǎn)品1</th>
<th>產(chǎn)品2</th>
<th>共同購買次數(shù)</th>
</tr>
{product_pairs_table}
</table>
</div>
<div class="section">
<h2>7. 銷售預(yù)測</h2>
<p>基于歷史數(shù)據(jù),預(yù)測未來7天的銷售額:</p>
<div class="chart">
<img src="data:image/png;base64,{forecast_chart}" alt="銷售預(yù)測圖">
</div>
</div>
<div class="section">
<h2>8. 結(jié)論與建議</h2>
<p>1. <strong>銷售策略</strong>:重點關(guān)注銷售額高的產(chǎn)品類別和產(chǎn)品,加大促銷力度。</p>
<p>2. <strong>客戶策略</strong>:針對高價值客戶,提供個性化服務(wù)和專屬優(yōu)惠,提高客戶忠誠度。</p>
<p>3. <strong>產(chǎn)品策略</strong>:基于產(chǎn)品關(guān)聯(lián)分析,優(yōu)化產(chǎn)品布局和推薦系統(tǒng),提高交叉銷售。</p>
<p>4. <strong>庫存管理</strong>:根據(jù)銷售趨勢和預(yù)測,合理安排庫存,避免積壓和缺貨。</p>
<p>5. <strong>支付方式</strong>:優(yōu)化支付流程,支持更多便捷的支付方式,提高轉(zhuǎn)化率。</p>
</div>
</body>
</html>
"""
# 生成圖表并轉(zhuǎn)換為base64
import base64
# 銷售趨勢圖
plt.figure(figsize=(12, 6))
sales_by_date.plot()
plt.title('每日銷售趨勢')
plt.xlabel('日期')
plt.ylabel('銷售額')
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
sales_trend_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 產(chǎn)品類別銷售圖
plt.figure(figsize=(12, 6))
sales_by_category.plot(kind='bar')
plt.title('各產(chǎn)品類別銷售額')
plt.xlabel('產(chǎn)品類別')
plt.ylabel('銷售額')
plt.xticks(rotation=45)
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
category_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 產(chǎn)品銷售圖
plt.figure(figsize=(12, 6))
top_10_products.plot(kind='bar')
plt.title('銷售額前10的產(chǎn)品')
plt.xlabel('產(chǎn)品名稱')
plt.ylabel('銷售額')
plt.xticks(rotation=45)
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
product_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 客戶消費分布圖
plt.figure(figsize=(12, 6))
sns.histplot(customer_purchase['總消費'], bins=20)
plt.title('客戶總消費分布')
plt.xlabel('總消費')
plt.ylabel('客戶數(shù)')
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
customer_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 支付方式分布圖
plt.figure(figsize=(10, 6))
plt.pie(payment_method_count, labels=payment_method_count.index, autopct='%1.1f%%')
plt.title('支付方式分布')
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
payment_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 銷售預(yù)測圖
plt.figure(figsize=(12, 6))
plt.plot(sales_series.index, sales_series.values, label='實際銷售額')
plt.plot(forecast.index, forecast.values, label='預(yù)測銷售額', linestyle='--')
plt.title('銷售額預(yù)測')
plt.xlabel('日期')
plt.ylabel('銷售額')
plt.legend()
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
forecast_chart = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
# 產(chǎn)品關(guān)聯(lián)表
product_pairs_table = ''
for _, row in product_pairs_df.head(10).iterrows():
product_pairs_table += f"<tr><td>{row['product1']}</td><td>{row['product2']}</td><td>{row['count']}</td></tr>"
# 填充報告數(shù)據(jù)
total_orders = len(df)
start_date = df['order_date'].min().strftime('%Y-%m-%d')
end_date = df['order_date'].max().strftime('%Y-%m-%d')
total_sales = df['total_amount'].sum()
total_customers = df['customer_id'].nunique()
total_products = df['product_name'].nunique()
top_category = sales_by_category.index[0]
top_category_percent = (sales_by_category.iloc[0] / total_sales) * 100
top_product = top_10_products.index[0]
top_product_sales = top_10_products.iloc[0]
top_customer_percent = (top_customers.sum() / customer_clv.sum()) * 100
top_payment_method = payment_method_count.idxmax()
top_payment_percent = (payment_method_count.max() / payment_method_count.sum()) * 100
# 生成最終報告
final_report = report_html.format(
total_orders=total_orders,
start_date=start_date,
end_date=end_date,
total_sales=total_sales,
total_customers=total_customers,
total_products=total_products,
top_category=top_category,
top_category_percent=top_category_percent,
top_product=top_product,
top_product_sales=top_product_sales,
top_customer_percent=top_customer_percent,
top_payment_method=top_payment_method,
top_payment_percent=top_payment_percent,
sales_trend_chart=sales_trend_chart,
category_chart=category_chart,
product_chart=product_chart,
customer_chart=customer_chart,
payment_chart=payment_chart,
product_pairs_table=product_pairs_table,
forecast_chart=forecast_chart
)
# 保存報告
with open('sales_analysis_report.html', 'w', encoding='utf-8') as f:
f.write(final_report)
print("分析報告已生成:sales_analysis_report.html")
項目總結(jié)
通過這個實戰(zhàn)項目,我們學(xué)習(xí)了如何使用 Python 進行數(shù)據(jù)分析,包括:
數(shù)據(jù)加載和預(yù)處理:使用 pandas 加載數(shù)據(jù),處理缺失值,轉(zhuǎn)換數(shù)據(jù)類型。
數(shù)據(jù)探索性分析:使用 pandas 進行數(shù)據(jù)統(tǒng)計,使用 matplotlib 和 seaborn 進行數(shù)據(jù)可視化。
數(shù)據(jù)深度分析:進行客戶價值分析、產(chǎn)品關(guān)聯(lián)分析和銷售預(yù)測。
生成分析報告:將分析結(jié)果整理成 HTML 報告,方便查看和分享。
技術(shù)??偨Y(jié)
- 數(shù)據(jù)處理:pandas, numpy
- 數(shù)據(jù)可視化:matplotlib, seaborn
- 時間序列分析:statsmodels
- 報告生成:HTML, base64
后續(xù)優(yōu)化方向
數(shù)據(jù)質(zhì)量:進一步提高數(shù)據(jù)質(zhì)量,處理異常值和重復(fù)值。
分析深度:使用更高級的分析方法,如聚類分析、分類分析等。
模型優(yōu)化:使用更復(fù)雜的預(yù)測模型,如 ARIMA、LSTM 等。
交互性:使用 dash 或 streamlit 構(gòu)建交互式分析應(yīng)用。
實時分析:搭建實時數(shù)據(jù)分析系統(tǒng),實時監(jiān)控銷售情況。
結(jié)論
Python 是一門非常適合數(shù)據(jù)分析的語言,它擁有豐富的庫和工具,可以幫助我們快速、高效地進行數(shù)據(jù)分析。作為一個從后端轉(zhuǎn) Rust 的萌新,我認為數(shù)據(jù)分析是一項非常重要的技能,無論是在后端開發(fā)還是其他領(lǐng)域,都能發(fā)揮重要作用。
通過這個實戰(zhàn)項目,我不僅鞏固了 Python 數(shù)據(jù)分析的技能,也對數(shù)據(jù)驅(qū)動決策有了更深刻的理解。我相信,在未來的工作中,這些技能將幫助我更好地解決問題,做出更明智的決策。
到此這篇關(guān)于Python項目實戰(zhàn):電商平臺銷售數(shù)據(jù)分析的文章就介紹到這了,更多相關(guān)Python電商平臺數(shù)據(jù)分析內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python數(shù)據(jù)分析之Matplotlib數(shù)據(jù)可視化
- Python數(shù)據(jù)分析應(yīng)用之Matplotlib數(shù)據(jù)可視化詳情
- Python數(shù)據(jù)分析進階之構(gòu)建可復(fù)用的數(shù)據(jù)處理類與模塊化腳本
- Python?Pandas數(shù)據(jù)分析的使用完整教學(xué)
- python數(shù)據(jù)分析中的多種圖形繪制示例(折線圖、柱狀圖、餅狀圖、散點圖、熱力圖)
- 使用Python對MySQL進行數(shù)據(jù)分析
- Python對時間序列進行數(shù)據(jù)分析與可視化的實戰(zhàn)指南
- Python數(shù)據(jù)分析必備的12種數(shù)據(jù)清洗技術(shù)分享
- Python進行數(shù)據(jù)分析的全流程指南
- Python進行數(shù)據(jù)分析的5大常見錯誤與解決
- Python分析寶馬全球銷售數(shù)據(jù)?實戰(zhàn)項目教你掌握數(shù)據(jù)清洗與可視化
相關(guān)文章
Python threading模塊中l(wèi)ock與Rlock的使用詳細講解
python的thread模塊是比較底層的模塊,python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用。這篇文章主要介紹了Python threading模塊中l(wèi)ock與Rlock的使用2022-10-10
基于Python的ModbusTCP客戶端實現(xiàn)詳解
這篇文章主要介紹了基于Python的ModbusTCP客戶端實現(xiàn)詳解,Modbus Poll和Modbus Slave是兩款非常流行的Modbus設(shè)備仿真軟件,支持Modbus RTU/ASCII和Modbus TCP/IP協(xié)議 ,經(jīng)常用于測試和調(diào)試Modbus設(shè)備,觀察Modbus通信過程中的各種報文,需要的朋友可以參考下2019-07-07
Python如何爬取51cto數(shù)據(jù)并存入MySQL
這篇文章主要介紹了Python如何爬取51cto數(shù)據(jù)并存入MySQL,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

