![](/img/trans.png)
[英]Getting count of unique values in pandas Dataframe when there is a list object in a column
[英]pandas dataframe count unique list
如果數據框中列的類型是int
、 float
或string
,我們可以使用columnName.unique()
獲取其唯一值。 但是如果這個列是一個列表,例如 [1, 2, 3] 呢? 我怎樣才能得到這個專欄的unique
之處?
我認為您可以將值轉換為元組,然后unique
效果很好:
df = pd.DataFrame({'col':[[1,1,2],[2,1,3,3],[1,1,2],[1,1,2]]})
print (df)
col
0 [1, 1, 2]
1 [2, 1, 3, 3]
2 [1, 1, 2]
3 [1, 1, 2]
print (df['col'].apply(tuple).unique())
[(1, 1, 2) (2, 1, 3, 3)]
L = [list(x) for x in df['col'].apply(tuple).unique()]
print (L)
[[1, 1, 2], [2, 1, 3, 3]]
您不能對不可散列的類型(例如列表unique()
應用unique()
。 您需要轉換為可散列類型才能做到這一點。
使用最新版本的 Pandas 的更好解決方案是使用duplicated()
並且避免迭代值以再次轉換為列表。
df[~df.col.apply(tuple).duplicated()]
這將作為列表返回唯一值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.