【问题标题】:Comparing two CSV files using lists and dictionaries使用列表和字典比较两个 CSV 文件
【发布时间】:2018-10-16 05:58:15
【问题描述】:

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

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

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

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

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) 

【问题讨论】:

  • 你能提供一些你的csv文件的数据样本吗?
  • 在数据样本中,您能否也告诉我们预期的输出应该是什么?
  • 已添加示例数据。
  • 我不太清楚你的意思戴夫,我想我解释得太多了。基本上,文件 2 具有与文件 1 相同的数据,但是两个文件的数据都比需要的多。过滤文件 2 以删除任何不必要的数据,我现在想使用过滤后的版本根据两个文件具有的列目标检索东向和北向。
  • 我是否正确假设您在文件 2 中的行数较少,因为已过滤掉不必要的行,现在您想从文件 1 中检索相应的行(那些与 Destination 共享相同值的行) )?

标签: python list dictionary


【解决方案1】:

根据 cmets 中的说明,我建议采用以下方法:

  1. 使用pandas.DataFrame 作为您选择的数据结构
  2. 加入您的列表

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

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 文件都带有标题行。

【讨论】:

  • 如果您只想使用来自file1 的列,您可以将data1 = data[['Destination', 'Easting', 'Northing']] 行添加到我上面的代码sn-p 以创建一个只有来自file2 的行的数据框和来自file1 的列(尽管有更有效的方法可以实现该结果,所以如果您需要,请告诉我,我会写一个详细的方法)。
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多