Python案例如何用Pandas做数据分组重采下线

wen python案例 5

本文目录导读:

Python案例如何用Pandas做数据分组重采下线

  1. 基础数据准备
  2. 按时间分组重采样
  3. 不同重采样方法的比较
  4. 实际业务案例:销售数据分析
  5. 按产品和门店分组重采样
  6. 月度环比分析
  7. 自定义重采样频率
  8. 处理缺失数据
  9. 数据透视表与重采样结合
  10. 性能优化建议

我来用Python的Pandas库演示数据分组重采样的几种常见案例。

基础数据准备

import pandas as pd
import numpy as np
from datetime import datetime
# 创建示例数据
np.random.seed(42)
# 创建时间序列数据
dates = pd.date_range('2024-01-01', periods=100, freq='H')
groups = ['A', 'B', 'C']
data = {
    'date': dates,
    'group': np.random.choice(groups, 100),
    'value': np.random.randn(100) * 10 + 50
}
df = pd.DataFrame(data)
print("原始数据前10行:")
print(df.head(10))

按时间分组重采样

# 设置日期为索引
df.set_index('date', inplace=True)
# 按组和时间重采样(每天的平均值)
daily_grouped = df.groupby('group').resample('D').mean()
print("按天重采样的平均值:")
print(daily_grouped.head(15))

不同重采样方法的比较

# 创建更多数据用于演示
df_hourly = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=48, freq='H'),
    'group': ['A'] * 24 + ['B'] * 24,
    'value': np.random.randint(10, 30, 48),
    'sales': np.random.randint(100, 500, 48)
})
# 按天重采样 - 不同聚合方式
df_hourly.set_index('date', inplace=True)
# 按组和天进行多种聚合
resampled = df_hourly.groupby('group').resample('D').agg({
    'value': ['mean', 'sum', 'count', 'std'],
    'sales': ['sum', 'mean', 'max']
})
print("多种聚合方式的重采样结果:")
print(resampled.head(10))

实际业务案例:销售数据分析

# 创建销售数据
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=200, freq='H')
products = ['手机', '电脑', '平板']
stores = ['北京店', '上海店', '广州店']
sales_data = pd.DataFrame({
    'date': np.random.choice(dates, 500),
    'product': np.random.choice(products, 500),
    'store': np.random.choice(stores, 500),
    'quantity': np.random.randint(1, 20, 500),
    'price': np.random.uniform(1000, 5000, 500),
    'amount': np.random.randint(1000, 50000, 500)
})
print("销售数据前5行:")
print(sales_data.head())

按产品和门店分组重采样

# 设置日期索引
sales_data.set_index('date', inplace=True)
# 按产品、门店分组,按周重采样
weekly_sales = sales_data.groupby(['product', 'store']).resample('W').agg({
    'quantity': 'sum',
    'amount': 'sum',
    'price': 'mean'
}).round(2)
print("\n按产品和门店的周度销售汇总:")
print(weekly_sales.head(20))

月度环比分析

# 创建月度数据
monthly_data = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=120, freq='D'),
    'category': np.random.choice(['电子产品', '服装', '食品'], 120),
    'sales': np.random.randint(10000, 100000, 120),
    'customers': np.random.randint(50, 500, 120)
})
# 按月重采样并计算环比
monthly_grouped = monthly_data.set_index('date').groupby('category').resample('M').sum()
# 添加环比增长率
for category in monthly_grouped.index.get_level_values(0).unique():
    mask = monthly_grouped.index.get_level_values(0) == category
    monthly_grouped.loc[mask, 'sales_growth'] = monthly_grouped.loc[mask, 'sales'].pct_change() * 100
print("\n月度环比分析(按类别):")
print(monthly_grouped.head(15))

自定义重采样频率

# 不同的时间频率
df_custom = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=100, freq='2H'),
    'region': np.random.choice(['东部', '西部', '南部', '北部'], 100),
    'revenue': np.random.randint(5000, 50000, 100)
}).set_index('date')
# 不同频率的重采样
frequencies = ['6H', '12H', 'D', 'W', 'M']
for freq in frequencies:
    result = df_custom.groupby('region').resample(freq)['revenue'].sum()
    print(f"\n按{freq}重采样的营收汇总:")
    print(result.head(10))

处理缺失数据

# 创建包含缺失值的数据
dates_with_gaps = pd.date_range('2024-01-01', periods=72, freq='H')
df_gap = pd.DataFrame({
    'date': dates_with_gaps,
    'sensor': np.random.choice(['温度', '湿度', '气压'], 72),
    'value': np.random.uniform(20, 30, 72)
})
# 人为制造缺失数据
df_gap.loc[10:15, 'value'] = np.nan
df_gap.loc[30:35, 'value'] = np.nan
# 使用不同的填充方法
df_gap.set_index('date', inplace=True)
# 按传感器分组,按天重采样,处理缺失值
cleaned_data = df_gap.groupby('sensor').resample('D').agg({
    'value': lambda x: x.mean() if len(x.dropna()) > 0 else x.ffill().mean()
}).round(2)
print("\n处理缺失值后的重采样结果:")
print(cleaned_data.head(20))

数据透视表与重采样结合

# 复杂的业务分析
pivot_data = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=180, freq='D'),
    'region': np.random.choice(['华北', '华东', '华南'], 180),
    'product_line': np.random.choice(['高端', '中端', '低端'], 180),
    'sales': np.random.randint(10000, 100000, 180),
    'profit': np.random.randint(1000, 20000, 180)
})
# 按季度和区域分析
quarterly_analysis = pivot_data.set_index('date').groupby(
    ['region', 'product_line']
).resample('Q').agg({
    'sales': ['sum', 'mean', 'std'],
    'profit': ['sum', 'mean']
}).round(2)
print("\n季度业务分析(按区域和产品线):")
print(quarterly_analysis.head(10))

性能优化建议

# 对于大数据集,可以使用以下方法优化性能
import time
# 方法1:使用多个聚合函数
def efficient_resampling(df, freq='D'):
    return df.groupby('group').resample(freq).agg({
        'value': ['mean', 'std', 'min', 'max']
    })
# 方法2:分批处理
def batch_resampling(df, batch_size=1000):
    results = []
    for start in range(0, len(df), batch_size):
        end = min(start + batch_size, len(df))
        batch = df.iloc[start:end]
        result = batch.groupby('group').resample('D').mean()
        results.append(result)
    return pd.concat(results)
print("""
性能优化建议:
1. 使用agg()代替多个resample调用
2. 使用合适的数据类型(category, datetime等)
3. 对于大数据集,考虑使用Dask或Vaex
4. 使用numba加速数值计算
5. 合理选择索引,避免不必要的排序
""")

这些案例涵盖了Pandas数据分组重采样的主要应用场景,关键点包括:

  1. 分组键设置:可以是单列或多列的组合
  2. 重采样频率:支持各种时间频率(H、D、W、M、Q、Y等)
  3. 聚合函数:可以同时使用多个聚合函数
  4. 缺失值处理:重采样时需要处理缺失数据
  5. 性能优化:对于大数据集要注意效率

根据你的具体业务需求选择合适的方法和频率。

抱歉,评论功能暂时关闭!