我有一个需要将数据框列的行转换为列的要求,但是在GROUPBY之后我遇到了一个问题。
以下是3个用户的集合,这些用户的类型可以在type1到type6之间。
user_id1 type4
user_id1 type6
user_id1 type1
user_id1 type2
user_id1 type1
user_id1 type6
user_id2 type1
user_id2 type2
user_id2 type2
user_id2 type1
user_id2 type3
user_id2 type4
user_id2 type5
user_id2 type6
user_id2 type2
user_id2 type6
user_id3 type1
user_id3 type2
user_id3 type3
user_id3 type2
我期望的输出是-
user_id type1 type2 type3 type4 type5 type6
user_id1 2 1 0 1 0 2
user_id2 2 3 1 1 1 2
user_id3 1 2 1 0 0 0
我试图对类型进行分组并得到计数。但不确定如何转换为列,尤其是缺少的类型应填充0。
非常感谢您的宝贵时间。
最佳答案
您需要使用的是pandas的pivot_table。您可以指定所需的行和列,fill_value声明要使用空值和aggfunc len计数执行的操作。
我不确定您的DataSeries是什么样子,但是您需要这样:
pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)
关于python - Python-分组后将行转换为列,并为不匹配的行填充零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43168493/