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

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

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

 importpandasaspd
 importnumpyasnp
 # 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)

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

1、resample

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

 importmatplotlib.pyplotasplt
 importseabornassns
 # 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")

在本例中,我们首先将' 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”表示月,等等。

closed:间隔是否应该在右侧(右)、左侧(左)或两侧(两个)闭合。

label :用它的结束(右)或开始(左)日期标记间隔。

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

 importmatplotlib.pyplotasplt
 importseabornassns
 # 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 ")3.Usingdtaccessorwithgroupby:

3、dt 访问器和 groupby

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

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

 importmatplotlib.pyplotasplt
 importseabornassns
 # 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)

总结

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

https://avoid.overfit.cn/post/9a7eac8d7fcb40709fae990f933609cf

作者:R. Gupta

目录
相关文章
|
28天前
|
数据格式 Python
如何使用Python的Pandas库进行数据透视图(melt/cast)操作?
Pandas的`melt()`和`pivot()`函数用于数据透视。基本步骤:导入pandas,创建DataFrame,然后使用这两个函数转换数据格式。示例代码展示了如何通过`melt()`转为长格式,再用`pivot()`恢复为宽格式。输入数据是包含'Name'和'Age'列的DataFrame,最终结果经过转换后呈现出不同的布局。
39 6
|
28天前
|
索引 Python
如何使用Pandas进行数据合并?
Pandas的`merge()`, `join()`, `concat()`是数据合并的主要工具。基本步骤包括导入pandas,创建DataFrame,然后执行合并。示例中,创建了两个DataFrame `df1`和`df2`,通过`merge()`和`join()`进行外连接合并。`merge()`基于索引合并,`join()`默认也使用索引合并,展示了数据融合的不同方式。
13 0
|
28天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,其DataFrame数据结构便于数据操作。筛选与过滤数据主要包括:导入pandas,创建DataFrame,通过布尔索引、`query()`或`loc[]`、`iloc[]`方法筛选。
|
29天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名?
Pandas在Python中提供数据排序和排名功能。使用`sort_values()`进行排序,如`df.sort_values(by='A', ascending=False)`进行降序排序;用`rank()`进行排名,如`df['A'].rank(ascending=False)`进行降序排名。多列操作可传入列名列表,如`df.sort_values(by=['A', 'B'], ascending=[True, False])`。
23 6
|
30天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行/列;3) `fillna()`用常数、前/后一个值填充;4) `interpolate()`插值填充。根据需求选择合适的方法处理数据缺失值。
15 0
|
30天前
|
索引 Python
如何在Python中,Pandas库实现对数据的时间序列分析?
Pandas在Python中提供强大的时间序列分析功能,包括:1) 使用`pd.date_range()`创建时间序列;2) 通过`pd.DataFrame()`将时间序列转为DataFrame;3) `set_index()`设定时间列作为索引;4) `resample()`实现数据重采样(如按月、季度);5) `rolling()`进行移动窗口计算,如计算移动平均;6) 使用`seasonal_decompose()`进行季节性调整。这些工具适用于各种时间序列分析场景。
28 0
|
3天前
|
数据挖掘 数据处理 索引
数据合并与连接:Pandas中的强大数据整合功能
【4月更文挑战第16天】Pandas是Python数据分析的库,提供数据合并与连接功能。本文聚焦于`merge`和`concat`函数。`merge`基于键合并DataFrame,如示例中`df1`和`df2`按'key'列合并,支持多种连接方式。`concat`则沿轴堆叠DataFrame,如`df3`和`df4`沿行连接。注意合并连接时键的一致性、选择合适连接方式及处理索引和数据结构,以确保数据准确一致。学习这些方法能有效整合多数据源,便于分析。
|
3天前
|
存储 数据库连接 数据处理
数据加载与保存:Pandas中的数据输入输出操作
【4月更文挑战第16天】Pandas是Python数据分析的强大工具,支持多种数据加载和保存方法。本文介绍了如何使用Pandas读写CSV和Excel文件,以及与数据库交互。`read_csv`和`to_csv`用于CSV操作,`read_excel`和`to_excel`处理Excel文件,而`read_sql`和`to_sql`则用于数据库的读写。了解这些基本操作能提升数据处理的效率和灵活性。
|
29天前
|
存储 Python
如何使用Pandas库对非数值型数据进行排序和排名?
在Pandas中,非数值型数据如字符串、日期和自定义类别也可排序。使用`sort_values()`对字符串列进行升序或降序排序,如`df.sort_values(by='Name', ascending=False)`。日期数据先用`pd.to_datetime()`转换,再排序。自定义排序可通过`argsort()`结合映射规则实现,例如根据预定义类别顺序排序。
18 7
|
29天前
|
数据可视化 Python
如何使用Python的Pandas库进行数据分组和聚合操作?
【2月更文挑战第29天】【2月更文挑战第105篇】如何使用Python的Pandas库进行数据分组和聚合操作?