python计算csv列中唯一元素的数量

2024-03-09

我正在尝试使用 Python 获取 csv 列中唯一项目的计数。

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

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

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

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)

这给出了以下格式的输出:

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 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python计算csv列中唯一元素的数量 的相关文章

随机推荐