如何查询淘宝消费汇总数据并分析个人消费习惯

引言
在数字消费时代,淘宝作为中国最大的电商平台之一,记录了我们大量的消费行为。了解自己的消费习惯不仅有助于合理规划财务,还能帮助我们做出更明智的购买决策。本文将详细介绍如何查询淘宝消费汇总数据,并通过这些数据进行个人消费习惯分析。我们将从数据获取、数据处理到数据分析的全过程进行讲解,并提供具体的代码示例和分析方法。
一、查询淘宝消费汇总数据
1.1 通过淘宝官方渠道获取数据
淘宝官方提供了多种方式供用户查询消费记录,最直接的方式是通过淘宝App或网页版查看订单历史。
步骤:
登录淘宝账号
:打开淘宝App或访问淘宝官网(www.taobao.com),使用你的账号登录。
进入“我的淘宝”
:在App底部导航栏点击“我的淘宝”,在网页版则点击右上角的“我的淘宝”。
查看订单历史
:在“我的淘宝”页面中,找到“我的订单”或“订单管理”选项,点击进入。
筛选和导出订单
:你可以按时间、状态(已完成、待付款等)筛选订单。淘宝目前不支持直接导出所有订单数据到Excel或CSV格式,但你可以手动记录或使用第三方工具(如浏览器插件)来辅助导出。
注意事项:
淘宝的订单数据通常保留最近3年左右,更早的数据可能无法直接查看。
部分敏感信息(如卖家联系方式)可能被隐藏。
1.2 使用第三方工具或脚本获取数据
由于淘宝官方不提供直接的数据导出功能,许多用户选择使用第三方工具或编写脚本来自动化获取订单数据。以下是一个基于Python的示例,使用Selenium模拟浏览器操作来获取订单数据。
示例代码:使用Selenium获取淘宝订单数据
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import csv

# 初始化浏览器驱动(这里以Chrome为例)
driver = webdriver.Chrome(executable_path=’你的Chrome驱动路径’)

# 登录淘宝
def login_taobao(username, password):
driver.get(‘https://www.taobao.com’)
# 点击登录按钮
login_btn = driver.find_element(By.LINK_TEXT, ‘登录’)
login_btn.click()
time.sleep(2)
# 输入用户名和密码
username_input = driver.find_element(By.ID, ‘fm-login-id’)
password_input = driver.find_element(By.ID, ‘fm-login-password’)
username_input.send_keys(username)
password_input.send_keys(password)
# 点击登录
driver.find_element(By.CLASS_NAME, ‘password-login’).click()
time.sleep(5) # 等待登录完成

# 获取订单数据
def get_orders():
driver.get(‘https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm’)
time.sleep(3)

orders = []
# 等待订单列表加载
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, ‘order-item’))
)

# 获取当前页面的订单
order_elements = driver.find_elements(By.CLASS_NAME, ‘order-item’)
for order in order_elements:
try:
# 获取订单号
order_id = order.find_element(By.CLASS_NAME, ‘order-id’).text
# 获取商品名称
item_name = order.find_element(By.CLASS_NAME, ‘item-title’).text
# 获取价格
price = order.find_element(By.CLASS_NAME, ‘price’).text
# 获取订单状态
status = order.find_element(By.CLASS_NAME, ‘status’).text
# 获取订单时间
time_str = order.find_element(By.CLASS_NAME, ‘time’).text

orders.append({
‘order_id’: order_id,
‘item_name’: item_name,
‘price’: price,
‘status’: status,
‘time’: time_str
})
except Exception as e:
print(f”Error processing order: {e}”)

return orders

# 主函数
if __name__ == ‘__main__’:
username = ‘你的淘宝账号’
password = ‘你的淘宝密码’

try:
login_taobao(username, password)
orders = get_orders()

# 将数据保存到CSV文件
with open(‘taobao_orders.csv’, ‘w’, newline=”, encoding=’utf-8′) as csvfile:
fieldnames = [‘order_id’, ‘item_name’, ‘price’, ‘status’, ‘time’]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for order in orders:
writer.writerow(order)

print(f”成功获取 {len(orders)} 条订单数据,已保存到 taobao_orders.csv”)
except Exception as e:
print(f”发生错误: {e}”)
finally:
driver.quit()
代码说明:
Selenium
:一个自动化测试工具,可以模拟浏览器操作。
登录函数
:
login_taobao
函数模拟登录过程,输入账号密码并点击登录。
获取订单函数
:
get_orders
函数进入订单页面,解析订单信息(订单号、商品名称、价格、状态、时间)。
数据保存
:将获取的订单数据保存为CSV文件,便于后续分析。
注意事项:
账号安全
:使用脚本时需谨慎,避免泄露账号密码。建议使用测试账号或虚拟环境。
反爬虫机制
:淘宝有反爬虫机制,频繁请求可能导致账号被限制。建议设置合理的请求间隔。
法律合规
:仅用于个人数据分析,不得用于商业用途或侵犯他人隐私。
1.3 使用浏览器插件
对于不熟悉编程的用户,可以使用浏览器插件(如“淘宝订单导出助手”)来导出订单数据。这些插件通常提供一键导出功能,将订单数据导出为Excel或CSV格式。
推荐插件:
淘宝订单导出助手
(Chrome扩展商店)
购物记录导出工具
(Firefox插件)
使用步骤:
在浏览器扩展商店搜索并安装插件。
登录淘宝账号,进入订单页面。
点击插件图标,选择导出选项。
选择导出的时间范围和数据字段,保存为CSV文件。
二、数据处理与清洗
获取到原始数据后,需要进行清洗和整理,以便进行分析。数据清洗包括去除重复数据、处理缺失值、格式化日期和价格等。
2.1 数据清洗示例
假设我们已经通过上述方法获取了订单数据,并保存为CSV文件。以下是一个使用Python的Pandas库进行数据清洗的示例。
示例代码:数据清洗
import pandas as pd
import numpy as np
from datetime import datetime

# 读取CSV文件
df = pd.read_csv(‘taobao_orders.csv’)

# 查看数据基本信息
print(“原始数据形状:”, df.shape)
print(“\n前5行数据:”)
print(df.head())
print(“\n数据类型:”)
print(df.dtypes)

# 数据清洗步骤
def clean_data(df):
# 1. 去除重复订单
df = df.drop_duplicates(subset=[‘order_id’])

# 2. 处理缺失值
# 如果价格或时间缺失,可以删除或填充(这里选择删除)
df = df.dropna(subset=[‘price’, ‘time’])

# 3. 格式化价格列
# 价格可能包含货币符号(如¥),需要转换为数值
df[‘price’] = df[‘price’].str.replace(‘¥’, ”).str.replace(‘,’, ”).astype(float)

# 4. 格式化时间列
# 将时间字符串转换为datetime对象
df[‘time’] = pd.to_datetime(df[‘time’], format=’%Y-%m-%d %H:%M:%S’)

# 5. 提取年份和月份
df[‘year’] = df[‘time’].dt.year
df[‘month’] = df[‘time’].dt.month
df[‘day’] = df[‘time’].dt.day

# 6. 添加消费类别(这里简单根据商品名称关键词分类)
def categorize_item(item_name):
item_name = item_name.lower()
if any(keyword in item_name for keyword in [‘衣服’, ‘衬衫’, ‘裤子’, ‘裙子’, ‘外套’]):
return ‘服装’
elif any(keyword in item_name for keyword in [‘手机’, ‘电脑’, ‘耳机’, ‘充电器’]):
return ‘电子产品’
elif any(keyword in item_name for keyword in [‘书’, ‘教材’, ‘杂志’]):
return ‘书籍’
elif any(keyword in item_name for keyword in [‘食品’, ‘零食’, ‘饮料’]):
return ‘食品’
elif any(keyword in item_name for keyword in [‘化妆品’, ‘护肤品’, ‘香水’]):
return ‘美妆’
else:
return ‘其他’

df[‘category’] = df[‘item_name’].apply(categorize_item)

return df

# 执行清洗
cleaned_df = clean_data(df)

# 保存清洗后的数据
cleaned_df.to_csv(‘cleaned_taobao_orders.csv’, index=False, encoding=’utf-8′)

print(“\n清洗后的数据形状:”, cleaned_df.shape)
print(“\n清洗后的前5行数据:”)
print(cleaned_df.head())
print(“\n数据类型:”)
print(cleaned_df.dtypes)
代码说明:
去除重复
:使用
drop_duplicates
方法去除重复的订单号。
处理缺失值
:删除价格或时间缺失的行。
格式化价格
:移除货币符号和逗号,转换为浮点数。
格式化时间
:将时间字符串转换为datetime对象,便于时间序列分析。
分类
:根据商品名称关键词进行简单分类,便于后续分析。
2.2 数据清洗的注意事项
数据完整性
:确保清洗后的数据尽可能完整,避免因删除过多数据而影响分析。
分类的准确性
:基于关键词的分类可能不准确,可以考虑使用更复杂的自然语言处理(NLP)方法。
数据安全
:清洗过程中注意保护个人隐私,避免泄露敏感信息。
三、个人消费习惯分析
数据清洗完成后,我们可以进行多维度的消费习惯分析。以下是一些常见的分析维度和方法。
3.1 消费金额分析
3.1.1 总消费金额和平均消费
计算总消费金额和平均消费金额,了解整体消费水平。
# 计算总消费金额
total_spending = cleaned_df[‘price’].sum()
average_spending = cleaned_df[‘price’].mean()

print(f”总消费金额: ¥{total_spending:.2f}”)
print(f”平均消费金额: ¥{average_spending:.2f}”)
3.1.2 月度消费趋势
分析每月的消费金额,观察消费趋势。
# 按月汇总消费金额
monthly_spending = cleaned_df.groupby([‘year’, ‘month’])[‘price’].sum().reset_index()
monthly_spending[‘date’] = monthly_spending[‘year’].astype(str) + ‘-‘ + monthly_spending[‘month’].astype(str).str.zfill(2)

# 绘制月度消费趋势图
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
plt.plot(monthly_spending[‘date’], monthly_spending[‘price’], marker=’o’)
plt.title(‘月度消费趋势’)
plt.xlabel(‘月份’)
plt.ylabel(‘消费金额 (¥)’)
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()
3.1.3 消费金额分布
分析消费金额的分布情况,了解消费的集中程度。
# 绘制消费金额分布直方图
plt.figure(figsize=(10, 6))
plt.hist(cleaned_df[‘price’], bins=30, edgecolor=’black’)
plt.title(‘消费金额分布’)
plt.xlabel(‘消费金额 (¥)’)
plt.ylabel(‘频数’)
plt.grid(True)
plt.show()
3.2 消费类别分析
3.2.1 各类别消费占比
分析不同消费类别的金额占比,了解消费结构。
# 按类别汇总消费金额
category_spending = cleaned_df.groupby(‘category’)[‘price’].sum().reset_index()
category_spending[‘percentage’] = category_spending[‘price’] / category_spending[‘price’].sum() * 100

# 绘制饼图
plt.figure(figsize=(8, 8))
plt.pie(category_spending[‘percentage’], labels=category_spending[‘category’], autopct=’%1.1f%%’)
plt.title(‘消费类别占比’)
plt.show()
3.2.2 各类别消费趋势
分析不同类别在不同时间的消费趋势。
# 按类别和月份汇总消费金额
category_monthly = cleaned_df.groupby([‘category’, ‘year’, ‘month’])[‘price’].sum().reset_index()
category_monthly[‘date’] = category_monthly[‘year’].astype(str) + ‘-‘ + category_monthly[‘month’].astype(str).str.zfill(2)

# 绘制类别消费趋势图
plt.figure(figsize=(12, 6))
for category in category_monthly[‘category’].unique():
data = category_monthly[category_monthly[‘category’] == category]
plt.plot(data[‘date’], data[‘price’], label=category, marker=’o’)

plt.title(‘各类别月度消费趋势’)
plt.xlabel(‘月份’)
plt.ylabel(‘消费金额 (¥)’)
plt.xticks(rotation=45)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
3.3 消费频率分析
3.3.1 每月消费次数
分析每月的消费次数,了解消费频率。
# 按月统计消费次数
monthly_count = cleaned_df.groupby([‘year’, ‘month’])[‘order_id’].count().reset_index()
monthly_count[‘date’] = monthly_count[‘year’].astype(str) + ‘-‘ + monthly_count[‘month’].astype(str).str.zfill(2)

# 绘制消费次数趋势图
plt.figure(figsize=(12, 6))
plt.plot(monthly_count[‘date’], monthly_count[‘order_id’], marker=’o’, color=’orange’)
plt.title(‘月度消费次数趋势’)
plt.xlabel(‘月份’)
plt.ylabel(‘消费次数’)
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()
3.3.2 消费间隔分析
分析两次消费之间的平均间隔天数,了解消费的规律性。
# 按时间排序
sorted_df = cleaned_df.sort_values(‘time’)

# 计算相邻订单的时间差
sorted_df[‘time_diff’] = sorted_df[‘time’].diff().dt.days

# 计算平均消费间隔
average_interval = sorted_df[‘time_diff’].mean()
print(f”平均消费间隔: {average_interval:.2f} 天”)

# 绘制消费间隔分布
plt.figure(figsize=(10, 6))
plt.hist(sorted_df[‘time_diff’].dropna(), bins=30, edgecolor=’black’)
plt.title(‘消费间隔分布’)
plt.xlabel(‘间隔天数’)
plt.ylabel(‘频数’)
plt.grid(True)
plt.show()
3.4 消费时间分析
3.4.1 每日消费时间分布
分析一天中不同时间段的消费情况。
# 提取小时
cleaned_df[‘hour’] = cleaned_df[‘time’].dt.hour

# 按小时统计消费金额和次数
hourly_spending = cleaned_df.groupby(‘hour’)[‘price’].sum().reset_index()
hourly_count = cleaned_df.groupby(‘hour’)[‘order_id’].count().reset_index()

# 绘制每小时消费金额和次数
fig, ax1 = plt.subplots(figsize=(12, 6))

color = ‘tab:red’
ax1.set_xlabel(‘小时’)
ax1.set_ylabel(‘消费金额 (¥)’, color=color)
ax1.plot(hourly_spending[‘hour’], hourly_spending[‘price’], color=color, marker=’o’)
ax1.tick_params(axis=’y’, labelcolor=color)

ax2 = ax1.twinx()
color = ‘tab:blue’
ax2.set_ylabel(‘消费次数’, color=color)
ax2.plot(hourly_count[‘hour’], hourly_count[‘order_id’], color=color, marker=’s’)
ax2.tick_params(axis=’y’, labelcolor=color)

plt.title(‘每小时消费金额和次数’)
plt.grid(True)
plt.show()
3.4.2 每周消费时间分布
分析一周中不同日期的消费情况。
# 提取星期几(0=周一,6=周日)
cleaned_df[‘weekday’] = cleaned_df[‘time’].dt.weekday

# 按星期几统计消费金额和次数
weekday_spending = cleaned_df.groupby(‘weekday’)[‘price’].sum().reset_index()
weekday_count = cleaned_df.groupby(‘weekday’)[‘order_id’].count().reset_index()

# 映射星期几的名称
weekday_names = [‘周一’, ‘周二’, ‘周三’, ‘周四’, ‘周五’, ‘周六’, ‘周日’]
weekday_spending[‘weekday_name’] = weekday_spending[‘weekday’].map(lambda x: weekday_names[x])
weekday_count[‘weekday_name’] = weekday_count[‘weekday’].map(lambda x: weekday_names[x])

# 绘制每周消费金额和次数
fig, ax1 = plt.subplots(figsize=(12, 6))

color = ‘tab:red’
ax1.set_xlabel(‘星期’)
ax1.set_ylabel(‘消费金额 (¥)’, color=color)
ax1.bar(weekday_spending[‘weekday_name’], weekday_spending[‘price’], color=color, alpha=0.6)
ax1.tick_params(axis=’y’, labelcolor=color)

ax2 = ax1.twinx()
color = ‘tab:blue’
ax2.set_ylabel(‘消费次数’, color=color)
ax2.bar(weekday_count[‘weekday_name’], weekday_count[‘order_id’], color=color, alpha=0.6)
ax2.tick_params(axis=’y’, labelcolor=color)

plt.title(‘每周消费金额和次数’)
plt.grid(True)
plt.show()
3.5 消费习惯总结与建议
基于以上分析,我们可以总结个人的消费习惯,并提出改进建议。
示例总结:
消费金额
:总消费金额为¥10,000,平均消费¥50/单,月度消费呈上升趋势,尤其在年底(11-12月)消费较高,可能与双十一、双十二促销有关。
消费类别
:电子产品占比最高(40%),其次是服装(30%),食品和美妆各占15%。说明你对科技产品和时尚服饰有较高兴趣。
消费频率
:平均每月消费10次,消费间隔平均为3天,说明消费较为频繁。
消费时间
:消费高峰在晚上8-10点,周末消费金额和次数明显高于工作日。
改进建议:
控制电子产品消费
:电子产品占比过高,可以考虑设定预算,避免冲动购买。
利用促销活动
:在双十一、双十二等促销期间集中购买必需品,节省开支。
分散消费时间
:避免在晚上消费高峰时段购物,减少冲动消费。
增加储蓄
:将每月消费的10%存入储蓄账户,用于应急或投资。
四、高级分析方法
4.1 使用机器学习进行消费预测
我们可以使用时间序列模型(如ARIMA)或机器学习模型(如随机森林)来预测未来的消费趋势。
示例:使用ARIMA模型预测月度消费
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 准备时间序列数据
ts_data = monthly_spending.set_index(‘date’)[‘price’]

# 绘制ACF和PACF图确定ARIMA参数
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
plot_acf(ts_data, ax=ax1, lags=20)
plot_pacf(ts_data, ax=ax2, lags=20)
plt.show()

# 拟合ARIMA模型(参数需根据ACF/PACF图调整)
model = ARIMA(ts_data, order=(1, 1, 1))
model_fit = model.fit()

# 预测未来3个月
forecast = model_fit.forecast(steps=3)
print(“未来3个月的预测消费金额:”)
for i, (date, value) in enumerate(forecast.items(), 1):
print(f”第{i}个月: ¥{value:.2f}”)

# 绘制预测结果
plt.figure(figsize=(12, 6))
plt.plot(ts_data.index, ts_data.values, label=’历史数据’)
plt.plot(forecast.index, forecast.values, label=’预测数据’, linestyle=’–‘)
plt.title(‘月度消费预测’)
plt.xlabel(‘月份’)
plt.ylabel(‘消费金额 (¥)’)
plt.legend()
plt.grid(True)
plt.show()
4.2 消费异常检测
使用统计方法或机器学习检测异常消费行为,如突然的高额消费。
示例:使用Z-score检测异常消费
from scipy import stats

# 计算Z-score
cleaned_df[‘z_score’] = np.abs(stats.zscore(cleaned_df[‘price’]))

# 定义异常阈值(通常Z-score > 3为异常)
threshold = 3
anomalies = cleaned_df[cleaned_df[‘z_score’] > threshold]

print(f”检测到 {len(anomalies)} 个异常消费记录:”)
print(anomalies[[‘order_id’, ‘item_name’, ‘price’, ‘time’]])

# 绘制异常消费点
plt.figure(figsize=(12, 6))
plt.scatter(cleaned_df[‘time’], cleaned_df[‘price’], alpha=0.6, label=’正常消费’)
plt.scatter(anomalies[‘time’], anomalies[‘price’], color=’red’, s=100, label=’异常消费’)
plt.title(‘消费异常检测’)
plt.xlabel(‘时间’)
plt.ylabel(‘消费金额 (¥)’)
plt.legend()
plt.grid(True)
plt.show()
4.3 消费关联分析
分析不同商品类别之间的购买关联性,例如购买手机后是否经常购买手机壳或充电器。
示例:使用Apriori算法进行关联规则挖掘
from mlxtend.frequent_patterns import apriori, association_rules

# 准备数据:将订单按类别进行独热编码
# 假设每个订单包含多个商品类别(这里简化处理,实际中需要按订单分组)
# 这里我们使用每个订单的类别列表(实际中可能需要更复杂的数据处理)
# 为简化,我们假设每个订单只有一个类别(实际中可能有多个)
# 更准确的做法是按订单分组,然后对类别进行独热编码

# 创建示例数据(实际中应从清洗后的数据中提取)
# 假设我们有订单和类别的对应关系
order_category = cleaned_df[[‘order_id’, ‘category’]].drop_duplicates()

# 创建独热编码矩阵
pivot_table = pd.get_dummies(order_category.set_index(‘order_id’)[‘category’]).groupby(level=0).sum()

# 使用Apriori算法找出频繁项集
frequent_itemsets = apriori(pivot_table, min_support=0.01, use_colnames=True)

# 生成关联规则
rules = association_rules(frequent_itemsets, metric=”confidence”, min_threshold=0.5)

print(“频繁项集:”)
print(frequent_itemsets)
print(“\n关联规则:”)
print(rules[[‘antecedents’, ‘consequents’, ‘support’, ‘confidence’, ‘lift’]])

# 可视化关联规则
import networkx as nx

# 创建图
G = nx.DiGraph()
for _, rule in rules.iterrows():
antecedents = list(rule[‘antecedents’])
consequents = list(rule[‘consequents’])
for ant in antecedents:
for con in consequents:
G.add_edge(ant, con, weight=rule[‘confidence’])

# 绘制网络图
plt.figure(figsize=(10, 8))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=2000, node_color=’lightblue’)
nx.draw_networkx_edges(G, pos, width=2, alpha=0.5, edge_color=’gray’)
nx.draw_networkx_labels(G, pos, font_size=10)
plt.title(‘商品类别关联规则网络图’)
plt.axis(‘off’)
plt.show()
五、数据可视化与报告生成
5.1 使用Matplotlib和Seaborn创建可视化图表
我们已经使用了Matplotlib进行基本绘图,现在可以使用Seaborn库创建更美观的图表。
示例:使用Seaborn创建综合消费报告
import seaborn as sns

# 设置Seaborn样式
sns.set_style(“whitegrid”)

# 创建画布
fig, axes = plt.subplots(2, 2, figsize=(15, 12))

# 1. 月度消费趋势
sns.lineplot(data=monthly_spending, x=’date’, y=’price’, ax=axes[0, 0])
axes[0, 0].set_title(‘月度消费趋势’)
axes[0, 0].tick_params(axis=’x’, rotation=45)

# 2. 消费类别占比
category_spending = cleaned_df.groupby(‘category’)[‘price’].sum().reset_index()
sns.barplot(data=category_spending, x=’category’, y=’price’, ax=axes[0, 1])
axes[0, 1].set_title(‘消费类别金额’)
axes[0, 1].tick_params(axis=’x’, rotation=45)

# 3. 每周消费分布
weekday_spending = cleaned_df.groupby(‘weekday’)[‘price’].sum().reset_index()
weekday_spending[‘weekday_name’] = weekday_spending[‘weekday’].map(lambda x: weekday_names[x])
sns.barplot(data=weekday_spending, x=’weekday_name’, y=’price’, ax=axes[1, 0])
axes[1, 0].set_title(‘每周消费金额’)
axes[1, 0].tick_params(axis=’x’, rotation=45)

# 4. 消费金额分布
sns.histplot(data=cleaned_df, x=’price’, bins=30, kde=True, ax=axes[1, 1])
axes[1, 1].set_title(‘消费金额分布’)
axes[1, 1].set_xlabel(‘消费金额 (¥)’)

plt.tight_layout()
plt.show()
5.2 生成消费分析报告
我们可以将分析结果整合成一份详细的消费分析报告,包括文字描述和图表。
示例:生成Markdown格式的报告
def generate_report(cleaned_df):
# 计算关键指标
total_spending = cleaned_df[‘price’].sum()
average_spending = cleaned_df[‘price’].mean()
total_orders = len(cleaned_df)

# 按类别汇总
category_spending = cleaned_df.groupby(‘category’)[‘price’].sum().reset_index()
category_spending[‘percentage’] = category_spending[‘price’] / total_spending * 100

# 按月份汇总
monthly_spending = cleaned_df.groupby([‘year’, ‘month’])[‘price’].sum().reset_index()
monthly_spending[‘date’] = monthly_spending[‘year’].astype(str) + ‘-‘ + monthly_spending[‘month’].astype(str).str.zfill(2)

# 生成Markdown报告
report = f”””# 淘宝消费分析报告

## 1. 总体消费情况
– **总消费金额**: ¥{total_spending:.2f}
– **平均消费金额**: ¥{average_spending:.2f}
– **总订单数**: {total_orders}

## 2. 消费类别分析
| 类别 | 消费金额 | 占比 |
|——|———-|——|
“””
for _, row in category_spending.iterrows():
report += f”| {row[‘category’]} | ¥{row[‘price’]:.2f} | {row[‘percentage’]:.1f}% |\n”

report += “””
## 3. 月度消费趋势
“””
# 添加月度消费表格
report += “| 月份 | 消费金额 |\n”
report += “|——|———-|\n”
for _, row in monthly_spending.iterrows():
report += f”| {row[‘date’]} | ¥{row[‘price’]:.2f} |\n”

report += “””
## 4. 消费习惯总结
基于以上分析,您的消费习惯如下:
1. **消费频率**: 平均每月消费 {monthly_spending[‘price’].mean():.1f} 次
2. **主要消费类别**: {category_spending.iloc[0][‘category’]} ({category_spending.iloc[0][‘percentage’]:.1f}%)
3. **消费高峰**: 通常在晚上8-10点,周末消费较多

## 5. 改进建议
1. 控制{category_spending.iloc[0][‘category’]}类别的消费,设定月度预算
2. 利用促销活动集中购买必需品
3. 增加储蓄比例,建议将每月消费的10%存入储蓄账户

—
*报告生成时间: {datetime.now().strftime(‘%Y-%m-%d %H:%M:%S’)}*
“””
return report

# 生成报告
report = generate_report(cleaned_df)

# 保存报告
with open(‘淘宝消费分析报告.md’, ‘w’, encoding=’utf-8′) as f:
f.write(report)

print(“报告已生成: 淘宝消费分析报告.md”)
print(“\n报告预览:”)
print(report[:500] + “…”)
六、隐私与安全注意事项
在进行个人消费数据分析时,必须注意保护个人隐私和数据安全。
6.1 数据安全措施
本地存储
:将数据存储在本地计算机,避免上传到云端或共享。
加密存储
:对敏感数据进行加密存储,使用强密码保护。
定期清理
:分析完成后,及时删除原始数据或加密备份。
6.2 法律合规
仅限个人使用
:数据仅用于个人分析,不得用于商业用途或分享给他人。
遵守平台规则
:使用自动化工具时,遵守淘宝的用户协议,避免违反反爬虫条款。
尊重隐私
:分析过程中不涉及他人隐私信息。
6.3 账号安全
避免使用真实账号
:建议使用测试账号或虚拟环境进行脚本测试。
定期更改密码
:定期更改淘宝账号密码,启用双重验证。
监控账号活动
:定期检查账号登录记录,发现异常及时处理。
七、总结
通过本文的指导,你可以系统地查询淘宝消费数据,并进行深入的个人消费习惯分析。从数据获取、清洗到多维度分析,我们提供了详细的步骤和代码示例。通过分析,你可以更好地了解自己的消费行为,制定合理的财务计划,并做出更明智的购买决策。
记住,数据分析的最终目的是帮助你改善生活,而不是增加焦虑。合理利用这些信息,让消费成为提升生活质量的工具,而不是负担。
附录:常用工具和资源
Python库
: Pandas, NumPy, Matplotlib, Seaborn, Scikit-learn, Statsmodels
浏览器插件
: 淘宝订单导出助手
数据可视化工具
: Tableau Public (免费版), Power BI
学习资源
: 《Python数据分析基础》, Coursera数据科学课程
希望本文对你有所帮助!如果你有任何问题或需要进一步的帮助,请随时提问。