繁体   English   中英

Pandas drop_duplicates 方法不适用于包含列表的数据框

[英]Pandas drop_duplicates method not working on dataframe containing lists

我试图在我的数据帧上使用 drop_duplicates 方法,但出现错误。 请参阅以下内容:

错误:类型错误:不可散列类型:“列表”

我正在使用的代码:

df = db.drop_duplicates()

我的数据库很大,包含字符串、浮点数、日期、NaN、布尔值、整数...任何帮助表示赞赏。

正如错误消息所暗示的那样, drop_duplicates 不适用于数据框中的列表。 但是,您可以删除转换为 str 的数据帧上的重复项,然后使用结果中的索引从原始 df 中提取行。

设置

df = pd.DataFrame({'Keyword': {0: 'apply', 1: 'apply', 2: 'apply', 3: 'terms', 4: 'terms'},
 'X': {0: [1, 2], 1: [1, 2], 2: 'xy', 3: 'xx', 4: 'yy'},
 'Y': {0: 'yy', 1: 'yy', 2: 'yx', 3: 'ix', 4: 'xi'}})

#Drop directly causes the same error
df.drop_duplicates()
Traceback (most recent call last):
...
TypeError: unhashable type: 'list'

解决方案

#convert hte df to str type, drop duplicates and then select the rows from original df.

df.loc[df.astype(str).drop_duplicates().index]
Out[205]: 
  Keyword       X   Y
0   apply  [1, 2]  yy
2   apply      xy  yx
3   terms      xx  ix
4   terms      yy  xi

#the list elements are still list in the final results.
df.loc[df.astype(str).drop_duplicates().index].loc[0,'X']
Out[207]: [1, 2]

编辑:用 loc 替换 iloc。 在这种特殊情况下,两者都在索引与位置索引匹配时起作用,但并不通用

@Allen 的回答很好,但有一个小问题。

df.iloc[df.astype(str).drop_duplicates().index]

在示例中,它应该是 loc 而不是 iloc.loot。

a = pd.DataFrame([['a',18],['b',11],['a',18]],index=[4,6,8])
Out[52]: 
   0   1
4  a  18
6  b  11
8  a  18

a.iloc[a.astype(str).drop_duplicates().index]
Out[53]:
...
IndexError: positional indexers are out-of-bounds

a.loc[a.astype(str).drop_duplicates().index]
Out[54]: 
   0   1
4  a  18
6  b  11

概览:可以看到哪些行重复了

方法一:

df2=df.copy()
mylist=df2.iloc[0,1]
df2.iloc[0,1]=' '.join(map(str,mylist))

mylist=df2.iloc[1,1]
df2.iloc[1,1]=' '.join(map(str,mylist))

duplicates=df2.duplicated(keep=False)
print(df2[duplicates])

方法二:

print(df.astype(str).duplicated(keep=False))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM