关于人工智能:在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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理