我有一个要求,需要将数据帧列的行转换为列,但是在 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 - 在分组后将行转换为列并为不匹配的行填充零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168493/