【问题标题】:Grouping a pandas dataframe with categorical strings使用分类字符串对 pandas 数据框进行分组
【发布时间】:2022-01-01 06:54:11
【问题描述】:

我有以下 df

df = pd.DataFrame({'Cat':['tq','tb','ta','tb','ta','tq','tb','tq','ta'],
                   'col1':['a','a','a','b','b','c','c','c','a'],
                   'col2':['aa','aa','aa','aa','ba','ba','cc','cc','cc'],
                   'val':np.random.rand(9)})

我想创建以下排名:

df['Cat'] = pd.Categorical(df['Cat'],['tb','tq','ta'])

但是,当我尝试按总和进行分组时:

df2 = df.groupby(['col1','Cat','col2'])['val'].sum()

我最终得到了一个 27 行的表,而不是我想要的 8 行,我省略了分类排名。

我知道 27 是 ['col1','Cat','col2'] 的唯一值的乘积。 我想知道如何通过过滤掉val != 0

【问题讨论】:

    标签: python pandas group-by categorical-data


    【解决方案1】:

    您可以在groupby 中使用observed 参数

    df2 = df.groupby(['col1','Cat','col2'], observed=True)['val'].sum()
    df2
    # col1  Cat  col2
    # a     tq   aa      0.422378
    #       tb   aa      0.395679
    #       ta   aa      0.407851
    #            cc      0.998086
    # b     tb   aa      0.318188
    #       ta   ba      0.861469
    # c     tq   ba      0.333660
    #            cc      0.427609
    #       tb   cc      0.415207
    # Name: val, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多