gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:10:24 24 4
gpt4 key购买 nike

我正在尝试在我的数据框上使用 drop_duplicates 方法,但我得到了一个错误。请参阅以下内容:

error: TypeError: unhashable type: 'list'

我使用的代码:

df = db.drop_duplicates()

我的数据库很大,包含字符串、 float 、日期、NaN、 bool 值、整数......感谢任何帮助。

最佳答案

如错误消息所示,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]

Edit: replaced iloc with loc. In this particular case, both work as the index matches the positional index, but it is not general

关于python - Pandas drop_duplicates 方法不适用于包含列表的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com