您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Pandasdrop_duplicates方法不起作用

Pandasdrop_duplicates方法不起作用

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。在这种特殊情况下,两者都作为索引与位置索引匹配而起作用,但这不是一般性的

其他 2022/1/1 18:40:29 有452人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶