繁体   English   中英

在 Python 中从 CSV 计算唯一值的最佳方法?

[英]Best way to count unique values from CSV in Python?

我需要一种快速计算 CSV 中唯一值的方法(例如,它是一个无法在 Excel 中打开的非常大的文件(> 100mb)),我想创建一个 python 脚本。

CSV 如下所示:

431231
3412123
321231
1234321
12312431
634534

我只需要脚本来返回文件中有多少不同的值。 例如,对于上述所需的输出将是:

6

到目前为止,这就是我所拥有的:

import csv
input_file = open(r'C:\Users\guill\Downloads\uu.csv')
csv_reader = csv.reader(input_file, delimiter=',')
thisdict = {
  "UserId": 1
}

for row in csv_reader:
    if row[0] not in thisdict:
        thisdict[row[0]] = 1

print(len(thisdict)-1)

似乎工作正常,但我想知道是否有更好/更有效/更优雅的方法来做到这一点?

集合比字典更适合这个问题:

with open(r'C:\Users\guill\Downloads\uu.csv') as f:
    input_file = f

csv_reader = csv.reader(f, delimiter=',')
uniqueIds = set()

for row in csv_reader:
    uniqueIds.add(row[0])

print(len(uniqueIds))

使用集合而不是字典,就像这样

import csv
input_file = open(r'C:\Users\guill\Downloads\uu.csv')
csv_reader = csv.reader(input_file, delimiter=',')
aa = set()
for row in csv_reader:
    aa.add(row[0])
print(len(aa))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM