python count number of unique elements in csv column

匆匆过客 提交于 2019-12-05 15:18:25

You're looking for the SeriesGroupby method nunique:

In [11]: df
Out[11]:
    0    1
0  AB  asd
1  AB  poi
2  AB  asd
3  BG  put
4  BG  asd

In [12]: g = df.groupby(0)

In [13]: g[1].nunique()
Out[13]:
0
AB    2
BG    2
Name: 1, dtype: int64

Use sets:

data = (('AB', 'asd'),
    ('AB', 'poi'),
    ('AB', 'asd'),
    ('BG', 'put'),
    ('BG', 'asd'))
unique_items = set(data)
keys = [[entry[0] for entry in unique_items]]
for key in set(keys):
    print("Key '{}' appears {} unique times".format(key, keys.count(key)))

Key 'BG' appears 2 unique times
Key 'AB' appears 2 unique times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!