熊猫drop_duplicates方法不起作用

SLa*_*k A 12 python pandas

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

错误:TypeError:无法散列的类型:“列表”

我正在使用的代码:

df = db.drop_duplicates()
Run Code Online (Sandbox Code Playgroud)

我的数据库很大,包含字符串,浮点数,日期,NaN,布尔值,整数...任何帮助,我们将不胜感激。

All*_*len 13

错误消息提示,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'
Run Code Online (Sandbox Code Playgroud)

#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]
Run Code Online (Sandbox Code Playgroud)

编辑:用loc替换了iloc。在这种特殊情况下,两者都作为索引与位置索引匹配而起作用,但这不是一般性的


Hsg*_*gao 6

@Allen的回答很好,但是有一点问题。

df.iloc[df.astype(str).drop_duplicates().index]
Run Code Online (Sandbox Code Playgroud)

在示例中,它应该是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
Run Code Online (Sandbox Code Playgroud)


小智 5

我还想提一下(以防其他人像我一样愚蠢),如果您错误地将列表列表作为 drop_duplicates 函数的“子集”参数,您将得到相同的错误。

结果我花了几个小时寻找一个不在我的数据框中的列表,因为我在参数中放置了一对多括号。