當我們的數據涉及日期和時間時,分析隨時間變化變得非常重要。Pandas提供了一種方便的方法,可以按不同的基于時間的間隔(如分鐘、小時、天、周、月、季度或年)對時間序列數據進行分組。
當我們的數據涉及日期和時間時,分析隨時間變化變得非常重要。Pandas提供了一種方便的方法,可以按不同的基于時間的間隔(如分鐘、小時、天、周、月、季度或年)對時間序列數據進行分組。

在Pandas中,有幾種基于日期對數據進行分組的方法。我們將使用這些虛擬數據進行演示:
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)

一些最常用的時間序列數據分組方法是:
1、resample
pandas中的resample 方法用于對時間序列數據進行重采樣,可以將數據的頻率更改為不同的間隔。例如將每日數據重新采樣為每月數據。Pandas中的resample方法可用于基于時間間隔對數據進行分組。它接收frequency參數并返回一個Resampler對象,該對象可用于應用各種聚合函數,如mean、sum或count。resample()只在DataFrame的索引為日期或時間類型時才對數據進行重新采樣。
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")


在本例中,我們首先將' 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一起按月間隔對數據進行分組:
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 ")3. Using dt accessor with groupby:


3、dt 訪問器和 groupby
Pandas中的dt訪問器可以從日期和時間類列中提取各種屬性,例如年、月、日等。所以我們可以使用提取的屬性根據與日期相關的信息對數據進行分組。
在Pandas中,使用dt訪問器從DataFrame中的date和time對象中提取屬性,然后使用groupby方法將數據分組為間隔。
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)

總結
這三種常用的方法可以匯總時間序列數據,所有方法都相對容易使用。在時間復雜度方面,所有方法對于中小型數據集都是有效的。對于較大的數據集,resample的性能更好,因為它針對時間索引進行了優化。而,Grouper和dt提供了更大的靈活性,可以進行更復雜的分組操作??梢愿鶕约合矚g的語法或者特定的需求選擇一種方法使用。