首页 > 解决方案 > 使用列表和字典比较两个 CSV 文件

问题描述

我有两个 CSV 文件,第一个有 3 列和多行,第二个有 4 列和多行,我正在尝试根据 RemoveDes 列表(在代码中)从第一个文件中检索数据,“RemovedDes”是经过过滤的文件 2 的版本,它已过滤掉文件 2 的目标列中第一个字母为“E”的数据行。并非文件 1 中的所有数据都将被使用,只有与 RemoveDes 对应的数据因此我为什么要使用需要比较两者。

如何仅打印文件 1 中的相关数据?

我知道这可能很容易做到,但我是新手,非常感谢任何帮助,干杯。

(为了进一步澄清;我在文件 1 中的 Eastings 和 Northings 之后,但需要使用“RemovedDes”(过滤掉 File2 中不必要的信息)来匹配两个文件中的数据)

File 1 Sample Data (many more rows):
Destination Easting Northing
    D4 .      102019 . 1018347
    D2 .      102385 . 2048908

File 2 Sample Data (many more rows):
Legend Destination Distance Width
 10       D4 .        67 .     87
 18       E2 .        32 .     44

请注意,E2 以 E. 开头时被过滤掉。请参阅下面的代码以进行说明。

Legend Destination Distance Width

    1stFile = open(file2.csv, 'r')
    FILE1 = 1stFile.readlines()
    print(FILE1)

  list_dictionary = []
    2ndFile = open(file2.csv, 'r') 
    FILE2 = 2ndFile.readlines()
    print(FILE2)
    for line in FILE2:
        values = line.split(',')
        Legend = values[0]
        Destination = values[1]
        Distance = values[2]
        Width = values[3]

        diction_list['LEG'] = Legend
        diction_list['DEST'] = Destination
        diction_list['DIST'] = Distance
        diction_list['WID'] = Width

        list_dictionary.append(the_dictionary)

    RemovedDes = [] 
    for line_dict in list_dictionary:
        if not li_dict['DEST'].startswith('E'): #Filters out rows of data which starts with the letter E in File 2.
            RemovedDes.append(li_dict)

    print(RemovedDes) 

标签: pythonlistdictionary

解决方案


根据评论中的澄清,我建议采用以下方法:

  1. 使用 apandas.DataFrame作为您选择的数据结构
  2. 执行您的列表的连接

以下代码将创建一个pandas数据框data,其中包含 的所有条目file2,并由它们在列中的相应条目扩展EastingNorthingfile1

import pandas as pd

file1 = pd.read_csv('file1.csv')
file2 = pd.read_csv('file2.csv')

data = pd.merge(file2, file1, how = 'left', on = 'Destination')

注意:这假设它Destination具有全面的唯一值,并且两个 .csv 文件都带有标题行。


推荐阅读