python drop_duplicates_Pandas drop_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]Edit: replaced iloc with loc. In this particular case, both work as the
index matches the positional index, but it is not general
總結
以上是生活随笔為你收集整理的python drop_duplicates_Pandas drop_duplicates方法不起作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php伪静态不支持中文,wordpres
- 下一篇: python 文本文件处理_53 Pyt