【问题标题】:Create new attribute in a dataframe on certain calculation在特定计算的数据框中创建新属性
【发布时间】:2022-01-08 02:05:51
【问题描述】:

考虑如下数据框:

customerid segment
1 active
1 viewed
1 addtocart
1 transacted
2 active
2 viewed
2 addtocart
3 active
3 viewed
4 active
5 active

如果我们看到:

活动段有:5 个客户 ID 已查看 3 addtocart 有 2 已成交 1

想要的是:

对于 customerid 1:此用户属于上述所有细分市场,我想在数据框中再创建一列,并将排名 1(因为它的 customerids 数量最少)给 customerid 的交易细分市场,对于其他 customerids 类似,我们得到如下的数据框

customerid segment Segment Priority
1 active 4
1 viewed 3
1 addtocart 2
1 transacted 1
2 active 3
2 viewed 2
2 addtocart 1
3 active 2
3 viewed 1
4 active 1
5 active 1

【问题讨论】:

    标签: pandas dataframe data-manipulation


    【解决方案1】:

    首先,制作第二个数据框,对段类型的值计数进行排名:

    df2 = pd.DataFrame(df['segment'].value_counts().rank(ascending=True)).reset_index()
    df2.columns = ['segment', 'count_rank']
    

    df2:

    segment count_rank
    active 4.0
    viewed 3.0
    addtocart 2.0
    transacted 1.0

    您可以将此数据框与您的原始数据框连接起来:

    df3 = df.merge(df2, on='segment').sort_values(['customerid', 'count_rank'], ascending=[True, False])

    customerid segment count_rank
    1 active 4.0
    1 viewed 3.0
    1 addtocart 2.0
    1 transacted 1.0
    2 active 4.0
    2 viewed 3.0
    2 addtocart 2.0
    3 active 4.0
    3 viewed 3.0
    4 active 4.0
    5 active 4.0

    但是,这是不正确的,因为您需要每个 customerid 的排名。 幸运的是,我们可以使用这个新列进行新的排名:

    df3['Segment Priority'] = df3.groupby('customerid')['count_rank'].rank()

    为了使它更漂亮的重置索引,删除辅助列并将 Segment Priority 设为 int 类型:

    df3.reset_index(drop=True).drop('count_rank', axis=1)
    df3['Segment Priority'] = df3['Segment Priority'].astype(int)
    

    结果:

    customerid segment Segment Priority
    1 active 4
    1 viewed 3
    1 addtocart 2
    1 transacted 1
    2 active 3
    2 viewed 2
    2 addtocart 1
    3 active 2
    3 viewed 1
    4 active 1
    5 active 1

    当然可以用更少的步骤来完成,或者将 df2 直接添加到 df.但是,这样我认为最清楚会发生什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 2023-03-08
      • 2016-10-16
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多