简体   繁体   English

从 Pandas 列中删除重复的字母只存在于彼此,Python

[英]Remove duplicated letters from pandas column exist only to each other, Python

from this question : Python: Best Way to remove duplicate character from string answer:来自这个问题: 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:

df=pd.DataFrame({'A':['ODOODY','LLHHEELLO'],'B':['NNMminee','DDasdss']})

expected result:预期结果:

A,B
ODODY,NMine
LHELO,Dasds

tried: df['A'] = df['A'].apply(lambda x: ''.join(ch for ch, _ in itertools.groupby(x['A']))) thanks !试过: 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:使用DataFrame.applymap ,如有必要,过滤列以删除重复项:

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

Solution with DataFrame.apply is possible, but need process each value separately, so aded list comprehension:使用DataFrame.apply解决方案是可能的,但需要单独处理每个值,因此添加列表理解:

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

Or use Series.apply :或使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 删除 Pandas 中的重复项,但保存其他列 PANDAS 中的值 - Remove duplicated in pandas but save values from other column PANDAS 如何从 python pandas 列中删除最后一个字母 - How to remove last letters from column python pandas 从每列中删除零并使用 python pandas/numpy 重新排列 - Remove zero from each column and rearranging it with python pandas/numpy 从每列中删除 NaN 并使用 python pandas/numpy 重新排列它 - Remove NaN from each column and rearranging it with python pandas/numpy 根据其他列从 Pandas dataframe 中删除重复项 - Remove duplicated from Pandas dataframe based on other columns Python、Pandas:检查列的列表值中的每个元素是否存在于其他 dataframe - Python, Pandas: check each element in list values of column to exist in other dataframe 如何从 Python Pandas 的 DataFrame 中的列中删除所有特殊字符和字母? - How to remove all special characters and letters from column in DataFrame in Python Pandas? Python/Pandas - 删除不重复的行 - Python/Pandas - remove not duplicated rows 从 Excel 文件列表创建 dataframe 以包括所有列和数据,即使列名在其他 Excel 文件中重复 - Python/Pandas - Creating a dataframe from list of Excel files to include all columns and data even if column name is duplicated in other Excel files - Python/Pandas Python Pandas 从另一列的列表中删除一列列表中的项目 - Python Pandas remove items from list in one column from the list in other column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM