python计数csv列中的唯一元素数 [英] python count number of unique elements in csv column

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

问题描述

我想使用Python获取csv列中唯一项目的计数。

I'm trying to get the counts of unique items in a csv column using Python.

示例CSV文件(没有标题):

Sample CSV file (has no header):

AB,asd
AB,poi
AB,asd
BG,put
BG,asd

$ b b

到目前为止我已经尝试过了。

I've tried this so far.

import csv
from collections import defaultdict, Counter

input_file = open('Results/1_sample.csv')
csv_reader = csv.reader(input_file, delimiter=',')

data = defaultdict(list)
for row in csv_reader:
    data[row[0]].append(row[1])
for k, v in data.items():
    print k
    print Counter(v)

这将提供以下格式的输出:

This gives output in this format:

AB
Counter({'asd': 2, 'poi': 1})
BG
Counter({'asd': 1, 'put': 1})

但我想要的输出如下:

AB:2
BG:2
total_unique_count:3 #unique count of column[1], irrespective of the data in column[0]


推荐答案

您正在寻找SeriesGroupby方法 nunique

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

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

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