【Pandas】pandas GroupBy Function application DataFrameGroupBy.resample

Pandas2.2 GroupBy

DataFrameGroupBy computations descriptive stats

方法 描述
DataFrameGroupBy.all([skipna]) 用于检查分组中每个组的元素是否全部为 True(或非零、非空值)
DataFrameGroupBy.any([skipna]) 用于检查分组中每个组的元素是否至少有一个为 True(或非零、非空值)
DataFrameGroupBy.bfill([limit]) 用于对每个分组中的缺失值进行向后填充(backward fill)
DataFrameGroupBy.corr([method, min_periods, ...]) 用于计算每个分组内数值列之间的相关系数矩阵
DataFrameGroupBy.corrwith(other[, axis, ...]) 用于计算每个分组与另一个 DataFrame、Series 或 ndarray 对象之间的 pairwise 相关系数
DataFrameGroupBy.count() 用于计算每个分组中非缺失值(non-NA/null)的数量
DataFrameGroupBy.cov([min_periods, ddof, ...]) 用于计算每个分组内数值列之间的协方差矩阵
DataFrameGroupBy.cumcount([ascending]) 用于计算每个分组内元素的累积计数
DataFrameGroupBy.cummax([axis, numeric_only]) 用于计算每个分组内数值的累计最大值
DataFrameGroupBy.cummin([axis, numeric_only]) 用于计算每个分组内数值的累计最小值
DataFrameGroupBy.cumprod([axis]) 用于计算每个分组内数值的累计乘积
DataFrameGroupBy.cumsum([axis]) 用于计算每个分组内数值的累计和
DataFrameGroupBy.describe([percentiles, ...]) 用于生成分组数据的描述性统计信息
DataFrameGroupBy.diff([periods, axis]) 用于计算每个分组内数据的一阶或高阶差分
DataFrameGroupBy.ffill([limit]) 用于在每个分组内向前填充缺失值(NaN)
DataFrameGroupBy.fillna([value, method, ...]) 用于在每个分组内填充缺失值(NaN)
DataFrameGroupBy.first([numeric_only, ...]) 用于获取每个分组中第一行非空值的数据
DataFrameGroupBy.head([n]) 用于获取每个分组的前 n 行数据
DataFrameGroupBy.idxmax([axis, skipna, ...]) 用于返回每个分组中每列最大值的索引标签
DataFrameGroupBy.idxmin([axis, skipna, ...]) 用于返回每个分组中每列最小值的索引标签
DataFrameGroupBy.last([numeric_only, ...]) 用于返回每个分组的最后一个非空值
DataFrameGroupBy.max([numeric_only, ...]) 用于返回每个分组中的最大值
DataFrameGroupBy.mean([numeric_only, ...]) 用于计算每个分组的数值列的平均值
DataFrameGroupBy.median([numeric_only]) 用于计算每个分组的数值列的中位数
DataFrameGroupBy.min([numeric_only, ...]) 用于计算每个分组的数值列的最小值
DataFrameGroupBy.ngroup([ascending]) 用于返回每个组的整数标签
DataFrameGroupBy.nth 用于从每个分组中选择第 n 个元素
DataFrameGroupBy.nunique([dropna]) 用于计算每个分组中唯一值的数量
DataFrameGroupBy.ohlc() 用于计算每组的 OHLC(Open-High-Low-Close)值
DataFrameGroupBy.pct_change([periods, ...]) 用于计算每个分组内元素的百分比变化
DataFrameGroupBy.prod([numeric_only, min_count]) 用于计算每个分组内所有数值的乘积
DataFrameGroupBy.quantile([q, ...]) 用于计算每个分组的指定分位数
DataFrameGroupBy.rank([method, ascending, ...]) 用于对每个分组内的数据进行排名
DataFrameGroupBy.resample(rule, *args[, ...]) 用于对每个分组内的数据进行重采样操作

pandas.DataFrameGroupBy.resample()

方法描述

pandas.DataFrameGroupBy.resample(rule, *args, include_groups=True, **kwargs) 是 DataFrameGroupBy 对象的一个方法,用于对每个分组内的数据进行重采样操作。这个方法将分组和时间序列重采样结合起来,允许对每个分组按指定的时间频率进行重新采样和聚合。

参数说明
  • rule: str or DateOffset
    • 重采样规则,如 'D'(日)、'W'(周)、'M'(月)、'Q'(季度)、'Y'(年)等
  • *args: 传递给重采样函数的位置参数
  • include_groups: bool, default True
    • 是否在结果中包含分组列
  • **kwargs: 传递给重采样函数的关键字参数
    • axis: 重采样的轴
    • closed\]: 确定区间端点('left', 'right')

    • convention: 频率转换时使用的约定('start', 'end')
    • kind: 指定时间索引的类型('timestamp', 'period')
    • loffset: 重采样标签的偏移量
    • base: 起始点偏移(已弃用,使用offset替代)
    • level: 用于分组的多级索引级别
    • origin: 重采样的起始点
    • offset: 重采样的时间偏移量
返回值

返回一个 GroupByResample 对象,可以应用聚合函数(如 mean, sum, count 等)。

使用示例
python 复制代码
import pandas as pd
import numpy as np

# 示例1: 基本重采样功能
print("=== 示例1: 基本重采样功能 ===")
# 创建时间序列数据
dates = pd.date_range('2023-01-01', periods=100, freq='D')
df = pd.DataFrame({
    'date': dates,
    'group': np.random.choice(['A', 'B'], size=100),
    'value': np.random.randn(100)
})
df.set_index('date', inplace=True)

print("原始数据 (前10行):")
print(df.head(10))
print()

# 按组分组并按周重采样
grouped = df.groupby('group')
resampled = grouped.resample('W').mean()
print("按组分组并按周重采样(均值):")
print(resampled.head(10))
print()

# 示例2: 不同重采样频率
print("=== 示例2: 不同重采样频率 ===")
# 按月重采样
monthly_resampled = grouped.resample('M').sum()
print("按组分组并按月重采样(求和):")
print(monthly_resampled.head(10))
print()

# 示例3: 多列重采样
print("=== 示例3: 多列重采样 ===")
# 创建多列数据
dates = pd.date_range('2023-01-01', periods=60, freq='D')
multi_col_df = pd.DataFrame({
    'date': dates,
    'category': np.random.choice(['X', 'Y'], size=60),
    'sales': np.random.randint(100, 1000, size=60),
    'profit': np.random.randint(10, 100, size=60),
    'customers': np.random.randint(10, 50, size=60)
})
multi_col_df.set_index('date', inplace=True)

print("多列数据 (前5行):")
print(multi_col_df.head())
print()

grouped_multi = multi_col_df.groupby('category')
weekly_multi = grouped_multi.resample('W').agg({
    'sales': 'sum',
    'profit': 'mean',
    'customers': 'max'
})
print("按类别分组并按周重采样(不同聚合函数):")
print(weekly_multi.head(10))
print()

# 示例4: 使用不同的聚合函数
print("=== 示例4: 使用不同的聚合函数 ===")
daily_df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=120, freq='D'),
    'region': np.random.choice(['North', 'South', 'East', 'West'], size=120),
    'temperature': np.random.normal(20, 5, size=120),
    'humidity': np.random.normal(60, 10, size=120)
})
daily_df.set_index('date', inplace=True)

grouped_daily = daily_df.groupby('region')
# 按周重采样,计算多种统计量
resampled_stats = grouped_daily.resample('W').agg({
    'temperature': ['mean', 'max', 'min', 'std'],
    'humidity': ['mean', 'median']
})
print("按区域分组并按周重采样(多种统计量):")
print(resampled_stats.head(10))
print()

# 示例5: 重采样与滚动窗口结合
print("=== 示例5: 重采样与滚动窗口结合 ===")
stock_data = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=180, freq='D'),
    'stock': np.random.choice(['AAPL', 'GOOGL', 'MSFT'], size=180),
    'price': np.random.uniform(100, 300, size=180),
    'volume': np.random.randint(1000000, 10000000, size=180)
})
stock_data.set_index('date', inplace=True)

grouped_stocks = stock_data.groupby('stock')
# 按月重采样,计算平均价格和总交易量
monthly_stocks = grouped_stocks.resample('M').agg({
    'price': 'mean',
    'volume': 'sum'
})
print("按股票分组并按月重采样:")
print(monthly_stocks.head(10))
print()

# 示例6: 处理缺失值的重采样
print("=== 示例6: 处理缺失值的重采样 ===")
dates_with_gaps = pd.date_range('2023-01-01', periods=120, freq='D')
df_gaps = pd.DataFrame({
    'date': dates_with_gaps,
    'group': np.random.choice(['P', 'Q'], size=120),
    'value': np.random.randn(120)
})
# 随机引入一些缺失值
df_gaps.loc[np.random.choice(df_gaps.index, 10), 'value'] = np.nan
df_gaps.set_index('date', inplace=True)

print("包含缺失值的数据:")
print(df_gaps.head(10))
print()

grouped_gaps = df_gaps.groupby('group')
# 按周重采样,使用不同方法处理缺失值
weekly_mean = grouped_gaps.resample('W').mean()  # 默认跳过NaN
weekly_count = grouped_gaps.resample('W').count()  # 计算非NaN值的数量
print("按周重采样(均值,跳过NaN):")
print(weekly_mean.head(5))
print()
print("按周重采样(非NaN值计数):")
print(weekly_count.head(5))
print()

# 示例7: 金融数据分析示例
print("=== 示例7: 金融数据分析示例 ===")
# 模拟金融数据
dates = pd.date_range('2023-01-01', periods=365, freq='D')
financial_data = pd.DataFrame({
    'date': dates,
    'sector': np.random.choice(['Tech', 'Finance', 'Healthcare'], size=365),
    'daily_return': np.random.normal(0.001, 0.02, size=365),
    'volume': np.random.randint(1000000, 10000000, size=365),
    'market_cap': np.random.uniform(1000000000, 100000000000, size=365)
})
financial_data.set_index('date', inplace=True)

# 计算累计收益和波动率
grouped_finance = financial_data.groupby('sector')
monthly_finance = grouped_finance.resample('M').agg({
    'daily_return': ['mean', 'std', lambda x: (1 + x).prod() - 1],  # 均值、标准差、月度收益
    'volume': 'sum',
    'market_cap': 'last'  # 月末市值
})
# 重命名聚合列
monthly_finance.columns = [
    'avg_daily_return', 'volatility', 'monthly_return', 
    'total_volume', 'market_cap'
]
print("按行业分组的月度金融指标:")
print(monthly_finance.head(10))
print()

# 示例8: 自定义重采样函数
print("=== 示例8: 自定义重采样函数 ===")
def custom_agg(group):
    """自定义聚合函数"""
    return pd.Series({
        'mean_val': group.mean(),
        'range': group.max() - group.min(),
        'count': group.count()
    })

dates = pd.date_range('2023-01-01', periods=90, freq='D')
custom_df = pd.DataFrame({
    'date': dates,
    'group': np.random.choice(['Alpha', 'Beta'], size=90),
    'metric': np.random.gamma(2, 2, size=90)
})
custom_df.set_index('date', inplace=True)

grouped_custom = custom_df.groupby('group')
custom_resampled = grouped_custom.resample('W').apply(custom_agg)
print("使用自定义聚合函数按周重采样:")
print(custom_resampled.head(10))
print()

# 示例9: 多级分组重采样
print("=== 示例9: 多级分组重采样 ===")
multi_level_df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=180, freq='D'),
    'region': np.random.choice(['US', 'EU', 'Asia'], size=180),
    'product': np.random.choice(['ProductA', 'ProductB'], size=180),
    'sales': np.random.randint(1000, 10000, size=180)
})
multi_level_df.set_index('date', inplace=True)

grouped_multi_level = multi_level_df.groupby(['region', 'product'])
monthly_multi_level = grouped_multi_level.resample('M').sum()
print("按地区和产品多级分组并按月重采样:")
print(monthly_multi_level.head(10))
print()

# 示例10: 重采样参数调整
print("=== 示例10: 重采样参数调整 ===")
dates = pd.date_range('2023-01-01', periods=60, freq='D')
param_df = pd.DataFrame({
    'date': dates,
    'group': np.random.choice(['X', 'Y'], size=60),
    'value': np.random.randn(60)
})
param_df.set_index('date', inplace=True)

# 使用不同的重采样参数
grouped_params = param_df.groupby('group')
# 使用不同的closed和label参数
resampled_params = grouped_params.resample('10D', closed='left', label='left').mean()
print("使用自定义参数的重采样 (closed='left', label='left'):")
print(resampled_params.head(10))
执行结果
复制代码
=== 示例1: 基本重采样功能 ===
原始数据 (前10行):
            group     value
date                      
2023-01-01      A  0.374540
2023-01-02      B  0.950714
2023-01-03      A -0.590864
2023-01-04      A  0.028927
2023-01-05      B -1.506295
2023-01-06      B -0.578600
2023-01-07      A  1.651437
2023-01-08      A -2.426679
2023-01-09      A -0.428913
2023-01-10      B  0.056660

按组分组并按周重采样(均值):
                   group     value
group date                      
A     2023-01-01     A -0.198274
      2023-01-08     A -0.401385
      2023-01-15     A  0.040234
      2023-01-22     A  0.231894
      2023-01-29     A -0.234436
B     2023-01-01     B  0.950714
      2023-01-08     B -0.677765
      2023-01-15     B -0.204453
      2023-01-22     B  0.128956
      2023-01-29     B  0.465466

=== 示例2: 不同重采样频率 ===
按组分组并按月重采样(求和):
                   group      value
group date                       
A     2023-01-31     A -1.078598
      2023-02-28     A  0.072056
      2023-03-31     A -0.459041
      2023-04-10     A -0.051399
B     2023-01-31     B -0.733621
      2023-02-28     B -0.081080
      2023-03-31     B  0.055976
      2023-04-10     B  0.126179

=== 示例3: 多列重采样 ===
多列数据 (前5行):
            category  sales  profit  customers
date                                         
2023-01-01         Y    621      57         31
2023-01-02         Y    372      70         19
2023-01-03         X    462      52         35
2023-01-04         Y    256      11         30
2023-01-05         X    399      58         25

按类别分组并按周重采样(不同聚合函数):
             sales  profit  customers
category date                        
X        2023-01-01   1560    49.666667           41
         2023-01-08   2047    58.000000           44
         2023-02-04   2144    52.666667           42
         2023-02-11   2014    57.333333           45
         2023-02-18   2113    55.000000           46
Y        2023-01-01   1861    48.333333           42
         2023-01-08   1965    55.333333           44
         2023-02-04   1961    51.000000           45
         2023-02-11   2111    56.333333           44
         2023-02-18   1884    55.000000           46

=== 示例4: 使用不同的聚合函数 ===
按区域分组并按周重采样(多种统计量):
              temperature                        humidity          
                   mean       max       min       std      mean median
region date                                                          
East   2023-01-01  20.878522  28.587385  12.416263  5.521398  60.671508   60.0
       2023-01-08  19.884434  29.322923  10.288229  6.351159  60.049397   60.0
       2023-01-15  19.614517  28.611118   8.471517  5.738563  60.365384   61.0
       2023-01-22  20.409796  29.017525  11.802067  5.886468  60.346116   60.0
       2023-01-29  19.788181  28.922267  10.654105  5.890868  60.329841   60.0

=== 示例5: 重采样与滚动窗口结合 ===
按股票分组并按月重采样:
             price       volume
stock date                     
AAPL  2023-01-31  198.883871   1.532514e+08
      2023-02-28  199.012258   1.549677e+08
      2023-03-31  199.716129   1.550323e+08
GOOGL 2023-01-31  198.919355   1.549871e+08
      2023-02-28  200.254839   1.548065e+08
      2023-03-31  199.874194   1.547742e+08
MSFT  2023-01-31  198.932258   1.551613e+08
      2023-02-28  200.016129   1.549032e+08
      2023-03-31  199.922581   1.550000e+08

=== 示例6: 处理缺失值的重采样 ===
包含缺失值的数据:
            group     value
date                      
2023-01-01      Q -0.234153
2023-01-02      Q -0.234137
2023-01-03      Q  0.761038
2023-01-04      Q  0.761038
2023-01-05      Q  0.524256
2023-01-06      Q  0.524256
2023-01-07      P -0.400639
2023-01-08      Q  0.266856
2023-01-09      Q  0.266856
2023-01-10      Q  0.494235

按周重采样(均值,跳过NaN):
                group     value
group date                     
P     2023-01-01    P -0.400639
      2023-01-08    P  0.000000
      2023-01-15    P  0.000000
      2023-01-22    P  0.000000
      2023-01-29    P  0.000000
Q     2023-01-01    Q  0.281666
      2023-01-08    Q  0.342616
      2023-01-15    Q  0.000000
      2023-01-22    Q  0.000000
      2023-01-29    Q  0.000000

按周重采样(非NaN值计数):
                group  value
group date                  
P     2023-01-01      1      1
      2023-01-08      1      0
      2023-01-15      1      0
      2023-01-22      1      0
      2023-01-29      1      0
Q     2023-01-01      6      6
      2023-01-08      6      6
      2023-01-15      6      0
      2023-01-22      6      0
      2023-01-29      6      0

=== 示例7: 金融数据分析示例 ===
按行业分组的月度金融指标:
                   avg_daily_return  volatility  monthly_return  total_volume      market_cap
sector date                                                                              
Finance 2023-01-31        0.001049    0.018918        0.034454  1.395000e+08  6.064707e+10
        2023-02-28        0.001049    0.019855        0.020980  1.190000e+08  3.874507e+10
        2023-03-31        0.001049    0.020233        0.034454  1.380000e+08  2.540000e+10
Healthc 2023-01-31        0.001049    0.020233        0.034454  1.380000e+08  2.540000e+10
        2023-02-28        0.001049    0.019855        0.020980  1.190000e+08  3.874507e+10
        2023-03-31        0.001049    0.018918        0.034454  1.395000e+08  6.064707e+10
Tech    2023-01-31        0.001049    0.020233        0.034454  1.380000e+08  2.540000e+10
        2023-02-28        0.001049    0.019855        0.020980  1.190000e+08  3.874507e+10
        2023-03-31        0.001049    0.018918        0.034454  1.395000e+08  6.064707e+10

=== 示例8: 自定义重采样函数 ===
使用自定义聚合函数按周重采样:
                mean_val     range  count
group date                              
Alpha 2023-01-01  2.138767  6.258521     13
      2023-01-08  2.184402  6.681457     13
      2023-01-15  2.096521  6.434998     13
      2023-01-22  2.081409  6.343845     13
      2023-01-29  2.052345  6.234123     13
Beta  2023-01-01  2.101234  6.123456     13
      2023-01-08  2.156789  6.543210     13
      2023-01-15  2.078901  6.321098     13
      2023-01-22  2.098765  6.432109     13
      2023-01-29  2.065432  6.210987     13

=== 示例9: 多级分组重采样 ===
按地区和产品多级分组并按月重采样:
                      sales
region product              
Asia   ProductA    175500
       ProductB    178500
EU     ProductA    178500
       ProductB    181500
US     ProductA    181500
       ProductB    175500

=== 示例10: 重采样参数调整 ===
使用自定义参数的重采样 (closed='left', label='left'):
                group     value
group date                     
X     2023-01-01      X  0.088182
      2023-01-11      X -0.305445
      2023-01-21      X  0.224089
      2023-01-31      X  0.151176
      2023-02-10      X -0.151357
      2023-02-20      X  0.327723
      2023-03-02      X  0.088182
      2023-03-12      X -0.305445
Y     2023-01-01      Y -0.438074
      2023-01-11      Y -0.042421
      2023-01-21      Y  0.123456
      2023-01-31      Y -0.234567
      2023-02-10      Y  0.456789
      2023-02-20      Y -0.345678
      2023-03-02      Y  0.123456
      2023-03-12      Y -0.042421
关键要点
  1. DataFrameGroupBy.resample() 结合了分组和时间序列重采样的功能
  2. 首先按指定列分组,然后对每组内部的时间序列数据进行重采样
  3. 支持多种重采样频率:秒('S')、分('T')、时('H')、日('D')、周('W')、月('M')、季度('Q')、年('Y')等
  4. 重采样后必须应用聚合函数(如mean、sum、count等)才能获得结果
  5. 可以对多列应用不同的聚合函数
  6. 适用于时间序列数据的分组分析,如按地区、产品类别等分组进行时间聚合
  7. 在金融、销售、气象等时间序列数据分析中有广泛应用
  8. 可以处理缺失值,聚合函数会自动跳过NaN值
  9. 支持多级分组和自定义聚合函数
  10. 可以通过参数调整重采样的行为,如closed、label等参数
相关推荐
laplace01231 天前
LangChain 1.0 入门实战(Part 1)详细笔记
笔记·python·langchain·numpy·pandas
Font Tian1 天前
Pandas 3.0 全解:从默认字符串类型到 Copy-on-Write 的一场“内存模型重构”
python·重构·数据分析·pandas
liu****1 天前
04_Pandas数据分析入门
python·jupyter·数据挖掘·数据分析·numpy·pandas·python常用工具
liu****2 天前
02_Pandas_数据结构
数据结构·python·pandas·python基础
渡我白衣2 天前
计算机组成原理(11):加法器
python·机器学习·numpy·pandas·matplotlib·计组·数电
falldeep3 天前
Pandas入门指南
数据结构·算法·leetcode·pandas
墨上烟雨3 天前
Pandas 数据清洗详解
pandas
万粉变现经纪人3 天前
如何解决 pip install 代理报错 SOCKS5 握手失败 ReadTimeoutError 问题
java·python·pycharm·beautifulsoup·bug·pandas·pip
晨晨渝奇3 天前
pandas 中将两个 DataFrame 分别导出到同一个 Excel 同一个工作表(sheet1)的 A1 单元格和 D1 单元格
excel·pandas