Python csv比较两个文件,如果两个值匹配,则更新值

2024-09-30 06:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

经过审查,很少有人推荐类似的关于比较价值的话题,对我帮助不大

car.csv

tittle1,tittle2
bmw,2000
mercedes,2000
toyota,1000
honda,1500
geely,500

price.csv

ori_price1,new_price2
2000,5000
1000,2500

结果应该是 标题1,标题2

bmw,5000
mercedes,5000
toyota,2500
honda,1500
geely,500

我发现下面的代码与结果非常接近

import csv

    with open('car.csv', 'r') as csv_file, open('price.csv', 'r', newline='') as csv_file2 \
            ,open('result.csv', 'w', newline='') as new_file:
        csv_reader = csv.DictReader(csv_file)
        csv_reader2 = csv.DictReader(csv_file2)
        csv_writer = csv.writer(new_file)

        csv_writer.writerow([ 'tittle1', 'title2'])

        for row1,row2 in zip(csv_reader,csv_reader2):
          csv_writer.writerow([row1['tittle1'],row1['tittle2'],row2['new_price2']])

Tags: csvnewasopencarmercedesfilewriter
1条回答
网友
1楼 · 发布于 2024-09-30 06:31:16

使用pandas,它可以非常简单:

import pandas as pd

cars=pd.read_csv("./cars.csv")
prices=pd.read_csv("./price.csv")

### iterate over the price changes as rows
for i,row in prices.iterrows(): 
    ### find where cars["tittle2"]==row["ori_price1"]
    #   and update column ['tittle2'] to row["new_price2"]
    cars.loc[cars["tittle2"]==row["ori_price1"], ['tittle2']] = row["new_price2"]

cars.to_csv("cars_updated.csv",index=False)

相关问题 更多 >

    热门问题