首页 > 解决方案 > 如何在忽略标点符号的数据框中删除重复项?

问题描述

我有以下数据框 -

  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 |

标签: pythonpandas

解决方案


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 + ' '])
['!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ']

推荐阅读