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

标签 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

我期望的输出是 -

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/

相关文章:

python - <键入 'exceptions.NameError' >

python - Pandas - 条形图和折线图 - 日期时间轴

python - 将图像转换为灰度

python - SQLITE创建语句错误

python - Pandas 检查时间序列的连续性

python - JSON 文件到 Pandas df

python - 在 Pandas Merge 上放置 WHERE 子句

python - 在 django 中使用 request.session ['value' 时出现 KeyError

python - 在 Python 中以秒和纳秒为单位获取 POSIX/Unix 时间?

python - 迭代每个 N 元素,放入一个元素(元组),然后每个 N 元素,放入另一个元素(元组)