python - 如何在忽略标点符号的数据框中删除重复项?
问题描述
我有以下数据框 -
print df
Name | Role |
Mark | Admin |
Mark | Admin. |
df = df.drop_duplicates()
print df
Name | Role |
Mark | Admin |
Mark | Admin. |
我想忽略任何前导或前面的标点符号(在这种情况下为句号)并删除重复项。
预期产出 -
df = df.drop_duplicates()
print df
Name | Role |
Mark | Admin |
解决方案
Series.str.strip
全部使用punctuations
,所有列使用空格DataFrame.apply
,获取所有重复项DataFrame.duplicated
并过滤boolean indexing
:
import string
df = df[~df.apply(lambda x: x.str.strip(string.punctuation + ' ')).duplicated()]
print (df)
Name Role
0 Mark Admin
另一个想法是使用 removed 处理数据punctuation
:
import string
df1 = df.apply(lambda x: x.str.strip(string.punctuation + ' ')).drop_duplicates()
print (df1)
Name Role
0 Mark Admin
细节
#added list for see last space
print ([string.punctuation + ' '])
['!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ']
推荐阅读
- python - datalloader函数,并且iter函数被清除,但是next()函数导致错误
- wagtail - 在流场块中内联创建片段 (Wagtail 2.3+)
- protege - swrl 规则不返回推断的属性
- email - 在共享应用程序中使用 MailApp sendEmail
- python - 在两个 @app.route 之间共享全局变量
- r - 使用 MICE 包进行插补后创建新变量
- python - 试图确定一个值是否是列表的一部分
- php - php页面重定向
- c# - 如何用单独的 Pins 替换 MapView?
- powershell - Powershell 在 Azure DevOps 中触发构建