pandas 通过对现有列的值进行计数来分组创建其他列 [英] pandas hwo to groupby create other columns by counting values of existing columns
本文介绍了 pandas 通过对现有列的值进行计数来分组创建其他列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何在R(
如何通过计算现有列来创建新列),但我也想知道它在python中的工作原理。
I got to know how to do this in R( How to make new columns by counting up an existing column), but I'd like also to know how it works in python as well.
当原始表格如下所示时
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对其分组,并希望它像
I group them by userID and want it come like
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
推荐答案
使用 融化
与 GroupBy.size
和 unstack
:
Use melt
with GroupBy.size
and unstack
:
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()
这篇关于 pandas 通过对现有列的值进行计数来分组创建其他列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文