python - 使用列表和字典比较两个 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)
解决方案
根据评论中的澄清,我建议采用以下方法:
- 使用 a
pandas.DataFrame
作为您选择的数据结构 - 执行您的列表的连接
以下代码将创建一个pandas
数据框data
,其中包含 的所有条目file2
,并由它们在列中的相应条目扩展Easting
和Northing
file1
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 文件都带有标题行。
推荐阅读
- php - 如果有 7 月 2 日和 7 月 2 日这样的两个日期,则根据日期选择数据,然后分别回显这两个数据
- javascript - HtmlUnit:click() 函数没有做任何事情
- python - 有没有办法更改熊猫数据透视表的边距“全部”列位置?
- yaml - yaml 格式的木偶螺栓计划
- git - 当我写 git commit -m "Complete chapter 1" 它不工作
- reactjs - 如何在 react-leaflet 中使用 setRotationAngle
- internet-explorer - X-UA 兼容 IE=10 不能在 EDGE 上运行
- c++ - linux“重命名”函数调用是否阻塞直到复制(当源和目标在不同磁盘中时)完成
- jquery - 用于 jquery .load() 的 BeforeSend
- json - 当我将以下脚本与 selenium 和 Beautifulsoup 一起使用时,文本被正确提取,但 json 文件始终相同