【问题标题】:How to include the counts for each character while removing the duplicates using itertools.groupby如何在使用 itertools.groupby 删除重复项时包含每个字符的计数
【发布时间】:2017-03-07 09:03:41
【问题描述】:

我有以下代码:

df= pd.DataFrame(data=all_r_1.to_dataframe().groupby(['user_id'])['type'].sum()).reset_index()

userid | type
20     | aab
21     | ababb

要从type 列中的字符串中删除重复项,我有以下代码:

df['type'] = df['type'].apply(lambda x: ''.join(ch for ch, _ in itertools.groupby(x)))

产生这个:

userid | type
20     | ab
21     | abab

这是输入df:

id | userid | type 
1  | 20     | a  
2  | 20     | a
3  | 20     | b
4  | 21     | a  
5  | 21     | b
6  | 21     | a
7  | 21     | b
8  | 21     | b

但是,我想做的是在删除重复项的同时包含每个字符的计数:

userid | type
20     | a2b
21     | abab2

有什么想法可以修改itertools.groupby 代码以包含计数吗?

【问题讨论】:

  • 试试这个:df['type'] = df['type'].apply(lambda x: ''.join(ch+len(list(group)) for ch, group in itertools.groupby(x)))
  • @Chris_Rands 谢谢!我收到此错误TypeError: object of type 'itertools._grouper' has no len()
  • 你输入len(list(group))了吗? (我将其编辑到我的原始评论中)
  • @Chris_Rands 是的,它有效,但我需要将其转换为 str。你能把这个作为答案发布吗?

标签: python string pandas itertools


【解决方案1】:

itertools.groupby 存储实际组,因此您可以按如下方式访问:

df['type'] = df['type'].apply(lambda x: ''.join('{}{}'.format(ch,len(list(group))) for ch, group in itertools.groupby(x)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2022-12-18
    • 2018-07-15
    • 2014-01-27
    相关资源
    最近更新 更多