Python 如何在使用itertools.groupby删除重复项时包含每个字符的计数
我有以下代码:Python 如何在使用itertools.groupby删除重复项时包含每个字符的计数,python,string,pandas,itertools,Python,String,Pandas,Itertools,我有以下代码: 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.gr
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代码以同时包含计数吗?itertools.groupby存储实际的组,以便您可以按如下方式访问:
df['type'] = df['type'].apply(lambda x: ''.join('{}{}'.format(ch,len(list(group))) for ch, group in itertools.groupby(x)))
尝试以下操作:df['type']=df['type'].applylambda x:.joinch+lenlistgroup for ch,itertools中的组。groupbyx@Chris_Rands谢谢我得到了一个错误TypeError:类型为“itertools.\u grouper”的对象没有lenDid,你把lenlistgroup放进去了吗?我把它编辑成我的原稿comment@Chris_Rands是的,它工作了,但我需要把它转换成str。你能把这个作为一个答案吗?