Python-比较两个csv文件中的重复值,并将行写入单独的csv文件中 - python

我有2个.csv文件,它们具有数千行数据(来自供应商的产品库存)。我需要找到重复的商品并删除价格较高的商品。

问题是价格包含小数。以下代码是我根据需要完成的最接近的代码:

with open('vendor1.csv', 'r') as venOne, open('vendor2.csv', 'r') as venTwo, open('filtered.csv', 'w') as outFile:

    z = csv.reader(venOne, delimiter = ',')
    m = csv.reader(venTwo, delimiter = ',')
    w = csv.writer(outFile, delimiter = ',')

    zupc = {row[5] for row in z}    #UPC is in column 5
    mupc = {row[5] for row in m}

    zprice = {row[9] for row in z}  #Price is in column 9
    mprice = {row[7] for row in m}  #Price is in column 7

    for row in z:
        if row[5] in mupc and row[9] < mprice:
            w.writerow(row)
        else:
            if row[5] not in mupc:
                w.writerow(row)

    #Do the same for m

我正在使用Python 2.x

最后,将使用cron作业运行该文件。所有数据都在远程共享服务器上。

需要注意的是,我无法使用pandas(使用我编写的其他各种脚本可以节省很多时间)。唯一可用的导入模块是python的标准导入模块,添加附加模块是不可能的(也就是说,无需花费更多的金钱来升级到专用服务器)。

参考方案

首先,您可能应该使用dict而不是set。关于价格,您可以尝试将其投射为decimal

尝试以下代码,让我知道这是否对您有帮助:

from decimal import Decimal

def write_cheaper_items(output, rows, this_prices, other_prices):
    for row in rows:
        upc = row[5]
        if upc not in other_prices or this_prices[upc] < other_prices[upc]:
            output.writerow(row)

with open('vendor1.csv', 'r') as venOne, open('vendor2.csv', 'r') as venTwo, open('filtered.csv', 'w') as outFile:
    z = csv.reader(venOne, delimiter = ',')
    m = csv.reader(venTwo, delimiter = ',')
    w = csv.writer(outFile, delimiter = ',')

    # these dicts will have the UPC as keys and their prices as values
    z_prices = {
        row[5]: Decimal(row[9])
        for row in z}
    m_prices = {
        row[5]: Decimal(row[7])
        for row in m}

    write_cheaper_items(w, z, z_prices, m_prices)
    write_cheaper_items(w, m, m_prices, z_prices)

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…