如何在 Pandas 中按月计算分类列?

Posted

技术标签:

【中文标题】如何在 Pandas 中按月计算分类列?【英文标题】:How can I count categorical columns by month in Pandas? 【发布时间】:2017-10-18 21:03:46 【问题描述】:

我的时间序列数据有一列可以取值 A、B 或 C。

我的数据示例如下所示:

date,category
2017-01-01,A
2017-01-15,B
2017-01-20,A
2017-02-02,C
2017-02-03,A
2017-02-05,C
2017-02-08,C

我想按月对我的数据进行分组,并将 A 的计数和 B 的计数的总和存储在 a_or_b_count 列中,并将 C 的计数存储在 c_count 中。

我已经尝试了几件事,但我能做的最接近的是使用以下函数预处理数据:

def preprocess(df):
    # Remove everything more granular than day by splitting the stringified version of the date.
    df['date'] = pd.to_datetime(df['date'].apply(lambda t: t.replace('\ufeff', '')), format="%Y-%m-%d")
    # Set the time column as the index and drop redundant time column now that time is indexed. Do this op in-place.
    df = df.set_index(df.date)
    df.drop('date', inplace=True, axis=1)
    # Group all events by (year, month) and count category by values.
    counted_events = df.groupby([(df.index.year), (df.index.month)], as_index=True).category.value_counts()
    counted_events.index.names = ["year", "month", "category"]
    return counted_events

这给了我以下信息:

year  month  category
2017  1      A           2
             B           1
      2      C           3
             A           1

总结所有 A 和 B 的过程将是相当手动的,因为在这种情况下类别成为索引的一部分。

我是一个绝对的熊猫威胁,所以我可能会比实际更难。任何人都可以提供有关如何在 pandas 中实现此分组的提示吗?

【问题讨论】:

【参考方案1】:

虽然我更喜欢@Scott Boston 的解决方案,但我尝试了这个,因为我之前结合了 A 和 B 值。

df.date = pd.to_datetime(df.date, format = '%Y-%m-%d')
df.loc[(df.category == 'A')|(df.category == 'B'), 'category'] = 'AB'

new_df = df.groupby([df.date.dt.year,df.date.dt.month]).category.value_counts().unstack().fillna(0)
new_df.columns = ['a_or_b_count', 'c_count']
new_df.index.names = ['Year', 'Month']

                a_or_b_count    c_count
Year    Month       
2017    1       3.0             0.0
        2       1.0             3.0

【讨论】:

预期输出是什么? 我比我更喜欢这个解决方案。

以上是关于如何在 Pandas 中按月计算分类列?的主要内容,如果未能解决你的问题,请参考以下文章

如何在bigquery中按月/年汇总

如何在熊猫中按两列计算唯一记录?

如何在 Pandas 中按年和月加入 2 个数据框?

如何在熊猫中按值计数对列进行排序

pandas 如何使用 groupby 在标签中按日期对列进行分组?

如何在 Pandas 数据框中按行值对日期时间列进行排序?