[英]add column from a csv file to another one
我想将名为“section_extract.csv”的 CSV 文件中的“坐标”列添加到另一个名为“prev_section.csv”的 csv 文件中。 两个 CSV 文件有一个名为"NOM"的公共列。
这就是名为“section_extract.csv”的 csv 文件的样子
这就是名为“prev_section.csv”的 csv 文件的样子
对我来说有点困难的是“坐标”必须由“NOM”分配。 我应该用对应于每个"NOM"的坐标填充 csv 文件"prev_section.csv " 。 例如:如果我们选择NOM = "PA62.565"我需要将对应的坐标填充到 csv 文件"prev_section.csv"中。
您可以在此处找到 2 个 CSV 文件: https://mega.nz/folder/FvxU2LzY#2NopozzSqgCOVeBezyiAcA
你可以试试这个。 我添加了一些评论以使其不言自明:
import csv
# We create a map (dict) having NOM as key and coords as value
with open('section_extract.csv') as file:
csv_reader = csv.reader(file, delimiter=';')
coord_map = {row[5]: row[1] for row in csv_reader}
# We extract the rows of the prev_section.csv file
with open('prev_section.csv') as file:
csv_reader = csv.reader(file, delimiter=';')
rows = [row for row in csv_reader]
# We will use this variable to keep track of the last read
# NOM, because in prev_section.csv the NOM is empty for some
# rows and it is meant to reference the last one
last_nom = None
# We add to the header a new column called 'coordinates'
rows[0].append('coordinates')
# We iterate the rows of prev_section.csv and add the coords
# values given a NOM, using the previously created map (dict)
for i in range(1, len(rows)):
row = rows[i]
# IMPORTANT: we update the last NOM every time we find
# a row that contains a value at this column
if row[0]:
last_nom = row[0]
row.append(coord_map.get(last_nom))
# We finally write in a 'prev_section2.csv' the same values
# as the original file but with the new 'coordinates' column
with open('prev_section2.csv', 'w') as file:
csv_writer = csv.writer(file, delimiter=';')
csv_writer.writerows(rows)
旁注:它可以在不创建rows
列表的情况下完成,并通过它重复,但我认为这里最好是明确的。 如果您需要更优化的解决方案,您只需提出要求即可:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.