我有两列,在数据框中每个单元格有很多重复项。类似于以下内容:

Index   x    y
  1     1    ec, us, us, gbr, lst
  2     5    ec, us, us, us, us, ec, ec, ec, ec
  3     8    ec, us, us, gbr, lst, lst, lst, lst, gbr
  4     5    ec, ec, ec, us, us, ir, us, ec, ir, ec, ec
  5     7    chn, chn, chn, ec, ec, us, us, gbr, lst

我需要消除所有重复项,并得到一个像这样的结果数据框:
Index   x    y
  1     1    ec, us, gbr, lst
  2     5    ec, us
  3     8    ec, us, gbr,lst
  4     5    ec, us, ir
  5     7    chn, ec, us, gbr, lst

谢谢!!

最佳答案

Split并应用setjoin

df['y'].str.split(', ').apply(set).str.join(', ')

0         us, ec, gbr, lst
1                   us, ec
2         us, ec, gbr, lst
3               us, ec, ir
4    us, lst, ec, gbr, chn
Name: y, dtype: object

根据评论更新:
df['y'].str.replace('nan|[{}\s]','').str.split(',').apply(set).str.join(',').str.strip(',').str.replace(",{2,}",",")

# Replace all the braces and nan with `''`, then split and apply set and join

关于python - 从数据框中的行和列(单元格)中删除重复项,python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48088686/

10-11 09:13