【问题标题】:pandas hwo to groupby create other columns by counting values of existing columns熊猫如何通过计算现有列的值来分组创建其他列
【发布时间】:2019-06-28 22:41:15
【问题描述】:

我知道如何在 R( How to make new columns by counting up an existing column),但我也想知道它在 python 中是如何工作的。

当原始表格如下图时

 userID   cat1    cat2
    a        f       3
    a        f       3
    a        u       1
    a        m       1
    b        u       2
    b        m       1
    b        m       2

我按用户 ID 对它们进行分组并希望它像

userID   cat1_f  cat1_m  cat1_u  cat2_1  cat2_2  cat2_3
a        2       1       1       2       0       1
b        0       2       1       1       2       0

【问题讨论】:

    标签: python pandas group-by count


    【解决方案1】:

    meltGroupBy.sizeunstack 一起使用:

    df = (df.melt('userID')
            .groupby(['userID','variable','value'])
            .size()
            .unstack([1,2], fill_value=0))
    #python 3.6+
    df.columns = [f'{a}_{b}' for a, b in df.columns]
    #python bellow
    #df.columns = ['{}_{}'.format(a,b) for a, b in df.columns]
    df = df.reset_index()
    print (df)
    RangeIndex(start=0, stop=7, step=1)
      userID  cat1_f  cat1_m  cat1_u  cat2_1  cat2_3  cat2_2
    0      a       2       1       1       2       2       0
    1      b       0       2       1       1       0       2
    

    替代crosstab:

    df = df.melt('userID')
    df = pd.crosstab(df['userID'], [df['variable'], df['value']])
    df.columns = [f'{a}_{b}' for a, b in df.columns]
    df = df.reset_index()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2013-08-30
      • 2022-06-10
      • 2017-09-17
      • 2018-06-23
      • 1970-01-01
      • 2015-09-19
      相关资源
      最近更新 更多