python - 从数据框中的行和列(单元格)中删除重复项,python

标签 python pandas dataframe

我有两列,数据框中的每个单元格都有很多重复项。类似这样的东西:

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]','', regex=True).str.split(',').apply(set).str.join(',').str.strip(',').str.replace(",{2,}",",", regex=True)

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

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

相关文章:

Python - Selenium 不会返回到上一页

python - 如何从 django 模板发布到 django 中的 View ?

python - 在 Pandas Dataframe 中查找非唯一行

r - 使用 "1"链接两个数据帧并提取相应的值

python - Scrapy 自定义导出器

python - 使用 numpy/h5py 进行内存高效的 Benjamini-Hochberg FDR 校正

python-3.x - Pandas 在导入 csv 文件时删除空格/未知字符

python - Pandas 转换 float 删除指数

python - dask groupby apply 中元数据的顺序

python - 从字符串列表中删除某些字符串作为 pandas.DataFrame 中的列