Skip to main content
 首页 » 编程设计

python之如何对时间序列数据进行分组

2025年05月04日12lonelyxmas

我下面有一个数据框,B 列的 dtype 是 datetime64。

    A      B 
0   a   2016-09-13 
1   b   2016-09-14 
2   b   2016-09-15 
3   a   2016-10-13 
4   a   2016-10-14 

我想按月分组(或者一般按年和日...)

所以我想得到下面的计数结果,key = B 列。

              a       b 
2016-09       1       2 
2016-10       2       0 

我试过groupby。但我不知道如何处理像 datetime64 这样的 dtypes... 如何处理和分组 dtype datetime64?

请您参考如下方法:

如果将索引设置为日期时间,则可以使用 pd.TimeGrouper 按不同的时间范围进行排序。示例代码:

# recreate dataframe 
df = pd.DataFrame({'A': ['a', 'b', 'b', 'a', 'a'], 'B': ['2016-09-13', '2016-09-14', '2016-09-15', 
                                                        '2016-10-13', '2016-10-14']}) 
df['B'] = pd.to_datetime(df['B']) 
 
# set column B as index for use of TimeGrouper 
df.set_index('B', inplace=True) 
 
# Now do the magic of Ami Tavory's answer combined with timeGrouper: 
df = df.groupby([pd.TimeGrouper('M'), 'A']).size().unstack().fillna(0) 

返回:

A             a    b 
B                    
2016-09-30  1.0  2.0 
2016-10-31  2.0  0.0 

或者(归功于 ayhan)跳过设置到索引步骤并在创建数据框后直接使用以下单行代码:

# recreate dataframe 
df = pd.DataFrame({'A': ['a', 'b', 'b', 'a', 'a'], 'B': ['2016-09-13', '2016-09-14', '2016-09-15', 
                                                        '2016-10-13', '2016-10-14']}) 
df['B'] = pd.to_datetime(df['B']) 
df = df.groupby([pd.Grouper(key='B', freq='M'), 'A']).size().unstack().fillna(0) 

返回相同的答案