【问题标题】:Python - convert rows to columns after group by and populate zeroes for non matching rowsPython - 在分组后将行转换为列并为不匹配的行填充零
【发布时间】:2017-08-27 08:48:42
【问题描述】:

我有一个要求,我需要将数据框列的行转换为列,但是在 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。

非常感谢您的宝贵时间。

【问题讨论】:

标签: python python-3.x pandas sklearn-pandas


【解决方案1】:

您需要使用的是 pandas 的 pivot_table。您可以指定所需的行和列,fill_value 说明您要对空值和 aggfunc len 计数做什么。

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

pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2017-10-22
    • 2015-12-19
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多