前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >在Pandas中通过时间频率来汇总数据的三种常用方法

在Pandas中通过时间频率来汇总数据的三种常用方法

原创
作者头像
用户6841540
发布2025-01-02 10:07:39
发布2025-01-02 10:07:39
6900
代码可运行
举报
运行总次数:0
代码可运行

当我们的数据涉及日期和时间时,分析随时间变化变得非常重要。Pandas提供了一种方便的方法,可以按不同的基于时间的间隔(如分钟、小时、天、周、月、季度或年)对时间序列数据进行分组。

比如进行数据分析时,我们需要将日数据转换为月数据,年数据等。

87dee3803595a4197c45a3d3d0fa576b.png
87dee3803595a4197c45a3d3d0fa576b.png

在Pandas中,有几种基于日期对数据进行分组的方法。我们将使用这些虚拟数据进行演示:

代码语言:python
代码运行次数:0
复制
    import pandas as pd  import numpy as np # generating data consisting of weekly sales for the timeperiod Jan,2022 to Jan,2023 
    dates =  pd.date_range('2022-01-01', '2023-01-05', freq = '1 W') sales_val = np.linspace(1000, 2000,len(dates) ) 
    data = {'date':dates,         'sales': sales_val}  # Load the data  df = pd.DataFrame(data)  # Convert the 'date' column to a datetime type  
    df['date'] = pd.to_datetime(df['date'])  df.sample(5)
9d783deda439e43eae77b810ca43bfab.png
9d783deda439e43eae77b810ca43bfab.png

一些最常用的时间序列数据分组方法是:

1. resample

pandas中的resample 方法用于对时间序列数据进行重采样,可以将数据的频率更改为不同的间隔。例如将每日数据重新采样为每月数据。Pandas中的resample方法可用于基于时间间隔对数据进行分组。它接收frequency参数并返回一个Resampler对象,该对象可用于应用各种聚合函数,如mean、sum或count。resample()只在DataFrame的索引为日期或时间类型时才对数据进行重新采样。

代码语言:python
代码运行次数:0
复制
    import matplotlib.pyplot as plt import seaborn as sns # Set the 'date' column as the index, # and Group the data by month using resample  grouped = df.set_index('date').resample('M').mean()  print("Grouping is done on monthly basis using resample method:\n", grouped) # plot the average of monthly sales sns.lineplot(grouped.index, grouped['sales']) plt.xlabel("Date") plt.ylabel("Average Monthly Sales") plt.grid(True) plt.title("Average Monthly sales with respect to month")
4ce7f237ca1f6bccd6c5a5b9089f5f39.png
4ce7f237ca1f6bccd6c5a5b9089f5f39.png
9e77fc61fe447114a7479bbf06f624f5.png
9e77fc61fe447114a7479bbf06f624f5.png

在本例中,我们首先将' date '列转换为日期类型,然后将其设置为DataFrame的索引。然后使用重采样方法按月分组数据,并计算每个月的“sales”列的平均值。结果是一个新的DF,每个月有一行,还包含该月“sales”列的平均值。

2. 使用Grouper

pandas的Grouper 函数可以与 groupby 方法一起使用,以根据不同的时间间隔(例如分钟、小时、天、周、月、季度或年)对数据进行分组。Grouper 包含了key (包含日期的列)、frequency (分组依据的间隔)、closed (关闭间隔的一侧)和label (标记间隔)等参数。Pandas 中的 Grouper 函数提供了一种按不同时间间隔(例如分钟、小时、天、周、月、季度或年)对时间序列数据进行分组的便捷方法。通过与Pandas 中的 groupby 方法 一起使用,可以根据不同的时间间隔对时间序列数据进行分组和汇总。

Grouper函数接受以下参数:

  • key: 时间序列数据的列名。
  • freq: 时间间隔的频率,如“D”表示日,“W”表示周,“M”表示月,等等。

具体freq的取值如下:

代码语言:bash
复制
        'D': 每天
        'B': 每个工作日(排除周末)
        'W': 每周
        'M': 每月最后一天
        'MS': 每月第一天
        'Q': 每季度最后一天
        'QS': 每季度第一天
        'Y': 每年最后一天
        'YS': 每年第一天

表示的是显示的时间,例如取Y时,会显示每年12/31;取YS时,显示的是1/1,但计算出的取值是一致的

详细取值可参考官方文档

  • closed: 间隔是否应该在右侧(右)、左侧(左)或两侧(两个)闭合。
  • label: 用它的结束(右)或开始(左)日期标记间隔。

Grouper函数和groupby一起按月间隔对数据进行分组:

代码语言:python
代码运行次数:0
复制
    import matplotlib.pyplot as plt 
    import seaborn as sns 
    # Group the data by month using pd.Grouper and calculate monthly average 
    grouped = df.groupby(pd.Grouper(key='date', freq='M')).mean() 
    print("Grouping is done on monthly basis using pandas.Grouper and groupby method:\n", grouped) 
    # plot the average of monthly sales sns.lineplot(grouped.index, grouped['sales']) plt.xlabel("Date") 
    plt.ylabel("Average Monthly Sales") 
    plt.grid(True) 
    plt.title("Average Monthly sales with respect to month using pd.Grouper and groupby ")
c2f016bf8494e12f259c62aba44de4ad.png
c2f016bf8494e12f259c62aba44de4ad.png
44637760e9312bb5c97d0f0f977f5055.png
44637760e9312bb5c97d0f0f977f5055.png

3. dt 访问器和 groupby

Pandas中的dt访问器可以从日期和时间类列中提取各种属性,例如年、月、日等。所以我们可以使用提取的属性根据与日期相关的信息对数据进行分组。

在Pandas中,使用dt访问器从DataFrame中的date和time对象中提取属性,然后使用groupby方法将数据分组为间隔。

代码语言:python
代码运行次数:0
复制
    import matplotlib.pyplot as plt 
    import seaborn as sns # Group the data by month using dt and calculate monthly average 
    grouped = df.groupby(df['date'].dt.to_period("M")).mean()
    print("Grouping is done on monthly basis using dt and groupby method:\n", grouped)
3e8760b1ded0b97278cf7eb8095a0682.png
3e8760b1ded0b97278cf7eb8095a0682.png

总结

这三种常用的方法可以汇总时间序列数据,所有方法都相对容易使用。在时间复杂度方面,所有方法对于中小型数据集都是有效的。对于较大的数据集,resample的性能更好,因为它针对时间索引进行了优化。而,Grouper和dt提供了更大的灵活性,可以进行更复杂的分组操作。可以根据自己喜欢的语法或者特定的需求选择一种方法使用。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. resample
  • 2. 使用Grouper
  • 3. dt 访问器和 groupby
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档