微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

查找不同 csv 文件之间列标题的差异

如何解决查找不同 csv 文件之间列标题的差异

我遇到了一个问题,我的 Pandas 连接遇到错误,无法找到某些标题在这种情况下,是“体验分数”列)。错误被抛出,但没有告诉我哪个文件导致了错误。我正在尝试减少尝试解决此问题的麻烦,并希望找到缺少我需要的标头或标头是否为错误的 dtype 等的实际文件

为了解决这个问题,我浏览了多个 csv 文件并试图找出每个文件中列标题间的差异。目前,这是我的流程:

def create_file_list(dir):
    # return a list of files for a directory specified in dir object
    return [os.path.join(dir,file) for file in os.listdir(dir)]

if __name__ == '__main__':
    dir = r'C:\Users\name\Documents\folder'

    # create a file list of all the files in the directory
    file_list = create_file_list(dir)

    # iterate over each file in the list,# pull out the headers of each file,# then compare if the headers are different from the desired header list (df)
    for path in file_list:
        try:
            data = pd.read_csv(path,dtype=str,header=2)
        except:
            data = pd.read_excel(path,header=2)
        df = pd.DataFrame(columns=['Date','Domain','Created Time','Experience score'])

我接下来要应用的伪代码是查看列是否不同,以告诉我哪些文件具有不同的标题

# find the file paths of files that have different headers from the df headers
if data.columns.difference(df.columns) > 0:
         print(path)

目前,使用 data.columns.difference(df.columns),我得到任一输出

1) Index(['Vertical Type (Product)'],dtype='object')
2) Index([],dtype='object')

但是这些并没有告诉我哪些文件有区别,哪些文件是相同的。

理想情况下,我希望输出结果如下:

1) C:\Users\name\Documents\folder\file_1.csv : Index(['Vertical Type (Product)'],dtype='object')
2) C:\Users\name\Documents\folder\file_2.csv : Index([],dtype='object')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。