【问题标题】:Remove duplicates from rows and columns (cell) in a dataframe, python从数据框中的行和列(单元格)中删除重复项,python
【发布时间】:2018-01-04 04:29:24
【问题描述】:

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

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

谢谢!!

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

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

【讨论】:

  • 它完美运行@Dark ...但我忘了包括所有 [y] 列都是这样的:{ec, us, us, gbr, lst, nan, nan}。我需要擦除 {} 和 nan。你知道怎么做吗?
  • @PAstudilloE 您是说 y 列类似于 {ec,us.. 在运行此代码之前还是在运行此代码之后?
  • 在运行代码之前。原始列是 {ec, us, ..., nan} @Dark
  • 效果很好。我现在唯一的问题是我得到的结果是这样的: , , us, ec... ( nan 被删除但逗号仍然存在)。您对如何解决这个问题有任何指导吗?
  • 对于 FutureWarning 错误添加 regex=True in replace
【解决方案2】:

试试这个:

d['y'] = d['y'].apply(lambda x: ', '.join(sorted(set(x.split(', ')))))

【讨论】:

  • 完美运行!...但我忘了包括所有 [y] 列都是这样的:{ec, us, us, gbr, lst, nan, nan}。我需要擦除 {} 和 nan。你知道怎么做吗?
【解决方案3】:

如果你不关心物品顺序,并且假设y列中所有内容的数据类型是字符串,你可以使用下面的sn-p:

df['y'] = df['y'].apply(lambda s: ', '.join(set(s.split(', '))))

set() 转换用于删除重复项。我认为在更高版本的 python 中它可能会保留顺序(也许是 3.4+?),但这是一个实现细节而不是语言规范。

【讨论】:

  • 不需要调用list
  • 我忘了包括所有 [y] 列都是这样的:{ec, us, us, gbr, lst, nan, nan}。我需要擦除 {} 和 nan。你知道怎么做吗?
  • 即使在 Python 3.10 中,sets 也是 documented as unordered collections,因此如果插入或枚举项目的顺序对程序很重要,则不应使用它们。
【解决方案4】:

在数据帧上使用apply 方法。

# change this function according to your needs
def dedup(row):
    return list(set(row.y))

df['deduped'] = df.apply(dedup, axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2019-05-04
    • 2015-03-11
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多