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

新手上路,请多包涵

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

错误:TypeError:无法散列的类型:’list’

我正在使用的代码:

 df = db.drop_duplicates()

我的数据库很大,包含字符串、浮点数、日期、NaN、布尔值、整数……感谢您的帮助。

原文由 SLack A 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 917
2 个回答

正如错误消息所暗示的那样,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]

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

原文由 Allen Qin 发布,翻译遵循 CC BY-SA 4.0 许可协议

@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

原文由 Hsgao 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题