实现思路
- 分块读取CSV文件:由于数据量大,内存无法一次性加载,使用Pandas的
chunksize
参数分块读取CSV文件,每次读取一部分数据进行处理,减少内存占用。
- 数据预处理:对每一块数据进行必要的预处理,比如数据类型转换,筛选需要的列等。
- 聚合数据:按商品类别和时间段对销售金额进行聚合,得到每个商品类别在不同时间段的销售金额总和。
- 绘制堆叠图:使用Matplotlib绘制堆叠图展示各类商品销售金额的变化趋势。
关键代码片段
import pandas as pd
import matplotlib.pyplot as plt
# 分块读取数据并聚合
file_paths = ['file1.csv', 'file2.csv', 'file3.csv'] # 假设多个CSV文件路径
aggregated_data = pd.DataFrame()
for file in file_paths:
for chunk in pd.read_csv(file, chunksize = 1000):
chunk['销售时间'] = pd.to_datetime(chunk['销售时间'])
# 假设商品ID前几位代表商品类别
chunk['商品类别'] = chunk['商品ID'].str.slice(stop = 3)
sub_agg = chunk.groupby(['商品类别', chunk['销售时间'].dt.to_period('M')])['销售金额'].sum().reset_index()
sub_agg = sub_agg.pivot(index = '销售时间', columns = '商品类别', values = '销售金额').fillna(0)
aggregated_data = pd.concat([aggregated_data, sub_agg])
aggregated_data = aggregated_data.groupby(aggregated_data.index).sum()
# 绘制堆叠图
aggregated_data.plot(kind='area', stacked = True)
plt.title('不同时间段内各类商品销售金额变化趋势')
plt.xlabel('时间段')
plt.ylabel('销售金额')
plt.show()