【问题标题】:How can I count categorical columns by month in Pandas?如何在 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 中实现此分组的提示吗?

【问题讨论】:

    标签: python-3.x pandas group-by time-series


    【解决方案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
    

    【讨论】:

    • 预期输出是什么?
    • 我比我更喜欢这个解决方案。
    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 2021-02-07
    • 2020-03-06
    • 1970-01-01
    • 2020-01-12
    • 2021-08-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多