gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:30 24 4
gpt4 key购买 nike

我下面有一个数据框,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)

返回相同的答案

关于python - 如何对时间序列数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39526134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com