从pandas列中删除仅存在的重复字母,Python [英] Remove duplicated letters from pandas column exist only to each other, Python
本文介绍了从pandas列中删除仅存在的重复字母,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自此问题: Python:从字符串中删除重复字符的最佳方法 答案:
''.join(ch for ch, _ in itertools.groupby(string_to_remove)
我知道如何删除彼此相邻的重复字母,如何将此解决方案应用于大熊猫中的列?
I know how to remove duplicated letters exists only next to each other, how to apply this solution to column in pandas?
df:
df=pd.DataFrame({'A':['ODOODY','LLHHEELLO'],'B':['NNMminee','DDasdss']})
预期结果:
A,B
ODODY,NMine
LHELO,Dasds
已尝试:
df['A'] = df['A'].apply(lambda x: ''.join(ch for ch, _ in itertools.groupby(x['A'])))
谢谢!
推荐答案
Use DataFrame.applymap
, if necessary filter columns for remove duplicates:
import itertools
cols = ['A','B']
df[cols] = df[cols].applymap(lambda x: ''.join(ch for ch, _ in itertools.groupby(x)))
#for all columns
#df = df.applymap(lambda x: ''.join(ch for ch, _ in itertools.groupby(x)))
print (df)
A B
0 ODODY NMmine
1 LHELO Dasds
使用 DataFrame.apply
是可能的,但需要分别处理每个值,因此可帮助您理解列表:
Solution with DataFrame.apply
is possible, but need process each value separately, so aded list comprehension:
df[cols] = df[cols].apply(lambda x: [''.join(ch for ch, _ in itertools.groupby(y)) for y in x])
print (df)
A B
0 ODODY NMmine
1 LHELO Dasds
或使用 Series.apply
:
Or use Series.apply
:
f = lambda x: ''.join(ch for ch, _ in itertools.groupby(x))
df['A'] = df['A'].apply(f)
df['B'] = df['B'].apply(f)
这篇关于从pandas列中删除仅存在的重复字母,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文