【问题标题】:Pandas Dataframe Groupby join string whilst preserving order of strings [duplicate]Pandas Dataframe Groupby加入字符串,同时保留字符串的顺序[重复]
【发布时间】:2021-11-19 07:40:59
【问题描述】:

已提出类似问题,即Concatenate strings from multiple rows using Pandas groupby and remove duplicates from the comma separated cell

我想在 pandas groupby lambda 函数中连接字符串值,但是在保持字符串顺序的同时,解决方案使用 set 函数,该函数在传入多个值时不保留顺序。

df = df.sort_values(
        ['id', 'order_column']
    ).groupby('id').agg(
        {
            'channel': lambda x: ' > '.join(set(x)),
            'value': np.sum
        }
    )

如何在保持传递给序列的值顺序的同时做到这一点?在我的例子中,数据是

1             Email
2         Affiliate
3    Organic Search
4             Email
5    Branded Social
6            Direct
7    Branded Social
8            Direct
9    Branded Social
10            Email
11        Affiliate
12            Email
13           Direct
14            Email
15           Direct
16            Email
17   Branded Social
18           Direct
19   Branded Social

我得到了什么:'Affiliate > Email > Organic Search > Branded Social > Direct'

我的期望'Email > Affiliate > Organic Search > Branded Social > Direct'

【问题讨论】:

    标签: python pandas string lambda pandas-groupby


    【解决方案1】:

    groupbydrop_duplicates 中使用sort=False 参数代替set

    df = df.sort_values(
            ['id', 'order_column']
        ).groupby('id', sort=False).agg(
            {
                'channel': lambda x: ' > '.join(x.drop_duplicates()),
                'value': np.sum
            }
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2020-07-28
      • 2022-01-23
      • 2018-10-05
      • 2020-12-23
      相关资源
      最近更新 更多