pandas 数据框计数唯一列表 [英] pandas dataframe count unique list

查看:32
本文介绍了 pandas 数据框计数唯一列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数据框中的列类型为 int float string ,则可以使用 columnName获得其唯一值.unique().但是如果此列是列表,例如[1、2、3].如何获得本专栏的 unique ?

If the type of a column in dataframe is int, float or string, we can get its unique values with columnName.unique(). But what if this column is a list, e.g. [1, 2, 3]. How could I get the unique of this column?

推荐答案

我认为您可以将值转换为元组,然后 unique 可以很好地工作:

I think you can convert values to tuples and then unique works nice:

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]]

这篇关于 pandas 数据框计数唯一列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆