![](/img/trans.png)
[英]'subset' not working for drop_duplicates pandas dataframe
[英]Pandas drop_duplicates method not working on dataframe containing lists
我試圖在我的數據幀上使用 drop_duplicates 方法,但出現錯誤。 請參閱以下內容:
錯誤:類型錯誤:不可散列類型:“列表”
我正在使用的代碼:
df = db.drop_duplicates()
我的數據庫很大,包含字符串、浮點數、日期、NaN、布爾值、整數...任何幫助表示贊賞。
正如錯誤消息所暗示的那樣, 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。 在這種特殊情況下,兩者都在索引與位置索引匹配時起作用,但並不通用
@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
概覽:可以看到哪些行重復了
方法一:
df2=df.copy()
mylist=df2.iloc[0,1]
df2.iloc[0,1]=' '.join(map(str,mylist))
mylist=df2.iloc[1,1]
df2.iloc[1,1]=' '.join(map(str,mylist))
duplicates=df2.duplicated(keep=False)
print(df2[duplicates])
方法二:
print(df.astype(str).duplicated(keep=False))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.