两个csv进行根据相同字段进行合并

源文件,第一列,编号0

目标文件, 编号3

根据社区名称进行匹配,然后将第一个csv文件的经纬度添加到第二个文件中。

import csv

source = r"D:\000datasets\链家房价数据\2020去重后社区名称地理编码.csv"
target = r"D:\000datasets\链家房价数据\链家网深圳二手房数据-2020.04.03 .csv"
# 打开源 CSV 文件并读取数据
with open(source, 'r',encoding='utf-8') as source_file:
    source_reader = csv.reader(source_file)
    source_data = list(source_reader)

# 打开目标 CSV 文件并读取数据
with open(target, 'r',encoding='utf-8') as target_file:
    target_reader = csv.reader(target_file)
    target_data = list(target_reader)

# 确定匹配字段的索引位置
match_field_index_source = 0
match_field_index_target = 3

# 在目标 CSV 文件中查找匹配的行,并复制字段的值
for source_row in source_data:
    match_value = source_row[match_field_index_source]

    for target_row in target_data:
        if target_row[match_field_index_target] == match_value:
            # 复制字段的值到目标文件
            target_row.append(source_row[1])
            target_row.append(source_row[2])

# 保存修改后的目标 CSV 文件
with open('target.csv', 'w', newline='',encoding='utf-8') as target_file:
    target_writer = csv.writer(target_file)
    target_writer.writerows(target_data)

使用chatgpt生成的。

如果你想将一个 CSV 文件的字段复制到另一个文件中,可以按照以下步骤进行操作:

1. 首先,使用 Python 的 `csv` 模块读取源 CSV 文件和目标 CSV 文件的数据。

import csv

# 打开源 CSV 文件并读取数据
with open('source.csv', 'r') as source_file:
    source_reader = csv.reader(source_file)
    source_data = list(source_reader)

# 打开目标 CSV 文件并读取数据
with open('target.csv', 'r') as target_file:
    target_reader = csv.reader(target_file)
    target_data = list(target_reader)

2. 确定源 CSV 文件和目标 CSV 文件中用于匹配的字段所在的索引位置。

假设源 CSV 文件和目标 CSV 文件中的匹配字段是第二列(索引位置为 1),你可以使用以下代码获取这些字段的位置:

# 确定匹配字段的索引位置
match_field_index_source = 1
match_field_index_target = 1

请根据实际情况调整索引位置。

3. 使用循环遍历源 CSV 文件的每一行,在目标 CSV 文件中查找匹配的行,并将相应字段的值复制到目标文件中。

# 在目标 CSV 文件中查找匹配的行,并复制字段的值
for source_row in source_data:
    match_value = source_row[match_field_index_source]

    for target_row in target_data:
        if target_row[match_field_index_target] == match_value:
            # 复制字段的值到目标文件
            target_row.append(source_row[field_index_to_copy])

# 保存修改后的目标 CSV 文件
with open('target.csv', 'w', newline='') as target_file:
    target_writer = csv.writer(target_file)
    target_writer.writerows(target_data)

在上述代码中,我们首先遍历源 CSV 文件的每一行,并提取用于匹配的字段值 `match_value`。

然后,我们在目标 CSV 文件中进行遍历,查找与 `match_value` 匹配的行。如果找到匹配的行,则将源 CSV 文件中要复制的字段值 `source_row[field_index_to_copy]` 添加到目标文件的当前行中。

最后,使用 `csv.writer()` 和 `writerows()` 方法将修改后的目标数据写入目标 CSV 文件。

请根据实际情况调整字段的索引位置和要复制的字段索引。确保源文件和目标文件的字段名称以及数据格式是相同的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CCCHHH333

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值