Python - 在分组后将行转换为列并为不匹配的行填充零

Sur*_*raj 5 python python-3.x pandas sklearn-pandas

我有一个要求,需要将数据帧列的行转换为列,但是在 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
Run Code Online (Sandbox Code Playgroud)

我期望的输出是 -

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
Run Code Online (Sandbox Code Playgroud)

我尝试对类型进行 groupby 并获得计数。但不确定如何转换为列,尤其是缺少的类型应该填充为 0。

非常感谢您抽出时间。

小智 7

您需要使用pandas 中的pivot_table。您可以指定所需的行和列,fill_value 说明您要如何处理空值和 aggfunc len 计数。

我不确定你的 DataSeries 是什么样子,但你需要这样的东西:

pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)
Run Code Online (Sandbox Code Playgroud)