繁体   English   中英

如何将Excel文件导入python并检查列是否重复?

[英]How do I import excel file to python and check column for duplicates?

我已经从一个包含7000多个不同选择的系统中收集了一些数据,我希望将该数据导入python并将A列(所有数据)视为列表,然后检查重复项。

理想的结果是将所有重复的选择都写入txt文件。

我偶然发现了可能会解决问题的单独代码,但是不知道如何编译它们以解决问题。

在下面查找重复项的代码-我当然会更改打印结果以写入文件...

def FindDuplicates(in_list):  
    unique = set(in_list)  
    for each in unique:  
        count = in_list.count(each)  
        if count > 1:  
            print 'There are duplicates in this list'  
            return True  
    print 'There are no duplicates in this list'  
    return False

我现在的工作基本上是用导入的excel文件的A列替换“ in_list”。

任何帮助或建议,将不胜感激。

干杯,杰克

您可以使用Python的Counter帮助确定是否存在重复项:

import xlrd
from collections import Counter

def FindDuplicates(in_list):
    counts = Counter(in_list)
    two_or_more = [item for item, count in counts.items() if count >= 2]
    print two_or_more
    return len(two_or_more) > 0

workbook = xlrd.open_workbook(r"input.xls")
sheet = workbook.sheet_by_index(0)
col_a = [sheet.row(row)[0].value for row in range(sheet.nrows)] # Read in all rows

print FindDuplicates(col_a)

默认情况下,Python无法读取.xls文件,因此您需要安装一个软件包以提供帮助。 我已使用xlrd读取旧格式的.xls文件。 可以使用以下方法安装:

pip install xlrd

如果您能够将Excel文件保存为.csv格式,则可以使用以下代码:

import csv
from collections import Counter

def FindDuplicates(in_list):
    counts = Counter(in_list)
    two_or_more = [item for item, count in counts.items() if count >= 2]
    print two_or_more
    return len(two_or_more) > 0

with open('input.csv', 'rb') as f_input:
    col_a = [row[0] for row in csv.reader(f_input)]

print FindDuplicates(col_a)

暂无
暂无

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

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