大熊猫如何GROUPBY通过计算现有列的值来创建其他列

问题描述 投票:1回答:1

我知道如何在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个回答
3
投票

使用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()
© www.soinside.com 2019 - 2024. All rights reserved.