我想在数据框上使用drop_duplicates方法,但是却出现了错误。如下所示:
错误:TypeError: unhashable type: 'list'
我使用的代码:
df = db.drop_duplicates()
我的数据库很大,包含字符串、浮点数、日期、NaN、布尔值、整数... 任何帮助都将不胜感激。
我想在数据框上使用drop_duplicates方法,但是却出现了错误。如下所示:
错误:TypeError: unhashable type: 'list'
我使用的代码:
df = db.drop_duplicates()
我的数据库很大,包含字符串、浮点数、日期、NaN、布尔值、整数... 任何帮助都将不胜感激。
drop_duplicates不能像错误信息所示那样处理数据框中的列表。但是,您可以在转换为str类型的数据框上删除重复项,然后使用结果中的索引从原始数据框中提取行。
设置
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,请看示例。
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
我还想提醒一下(如果有人像我一样傻),如果你错误地将一个列表的列表作为 drop_duplicates 函数的 'subset' 参数,你将会得到相同的错误。
结果发现我花了几个小时去寻找一个我的数据框中没有的列表,只是因为我在参数中多加了一些方括号。
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))