【问题标题】:How to update csv values given their row and column numbers are known with pythonpython - 给定行号和列号的情况下如何更新csv值
【发布时间】:2021-12-28 17:34:44
【问题描述】:

我有一些代码可以查看 .csv 文件的行并检查这些行是否包含来自另一个 .csv 文件的特定列的任何值。

这些文件如下所示:

查找文件:

0:  TextExclude, text, other
1:  aa,        , x ,   y
2:  bb,        , x ,   y
3:  cc,        , x ,   y

我要在其中找到这些值的文件:

0: x, longtext, exclude
1: x, helloaa,  0
2: x, testaa,   0
3: x, testcc,   0
4: x, no,       0
5: x, aabb,     0

我的代码的输出应该在除第 4 行之外的每一行中将“包含”列的值从 0 更改为 1,从而产生此 预期输出 csv 表:

0: x, longtext, exclude
1: x, helloaa,  1
2: x, testaa,   1
3: x, testcc,   1
4: x, no,       0
5: x, aabb,     1

由于我的代码可以输出找到匹配项的 行号 并且 列号 已经定义,我想知道解决此问题的最佳方法是什么并相应地更新 .csv 文件?

这是我的代码:

import pandas
findlist = []
linecount=0
       
with open('lookup.csv', 'r') as f:
    column_names = ["TextExclude", "Exclusion", "Filename"]
    r = pandas.read_csv(f, names=column_names)
    findlist = r.TextExclude.to_list()

with open('datafile.csv', 'r') as f:
    # Skip the first line
    f.readline()
    for line in f: 
        linecount = linecount +1
        if any(listelement in line for listelement in findlist):
            print(line)

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    您应该使用 pandas 解析 datafile.csv,而不仅仅是将其读取为纯文本文件。这样一来,您就可以将搜索隔离到正确的列,并更轻松地更新第三列。

    import pandas
    findlist = []
    linecount=0
    
    with open('lookup.csv', 'r') as f:
        column_names = ["TextExclude", "Exclusion", "Filename"]
        r = pandas.read_csv(f, names=column_names)
        findlist = r.TextExclude.to_list()
    
    with open('datafile.csv', 'r') as f:
        df = pandas.read_csv(f)
        for ri, row in df.iterrows():
            if any(x in row[1] for x in findlist):
                row[2] = "1"
    
    # print result to stdout
    print(df)
    
    # or write result to a file:
    df.to_csv("output.csv")
    

    如果您想知道您使用的是什么版本的 Pandas 和 Python,您可以运行以下两个命令:

    Python 版本:
    python --version

    熊猫版:
    python -c "import pandas;print(pandas.__version__)"

    这是第二种搜索方式,它可以将步骤分解得更细一些,这可能有助于调试:

    import pandas
    findlist = []
    linecount=0
    
    with open('lookup.csv', 'r') as f:
        column_names = ["TextExclude", "Exclusion", "Filename"]
        r = pandas.read_csv(f, names=column_names)
        findlist = r.TextExclude.to_list()
    
    def search(search_in):
        for to_find in findlist:
            if to_find in search_in:
                return True
        return False
    
    with open('datafile.csv', 'r') as f:
        df = pandas.read_csv(f)
        for ri, row in df.iterrows():
            if search(row[1]):
                row[2] = "1"
    
    # print result to stdout
    print(df)
    
    # or write result to a file:
    df.to_csv("output.csv")
    

    【讨论】:

    • 感谢您的回答,我已复制此代码但收到 TypeError:第 13 行的“float”类型参数不可迭代。由于我对 python 很陌生,我找不到原因对于这个问题。
    • 您是否将我的程序复制并粘贴到一个新的 python 文件中并在没有任何其他代码的情况下单独运行它?这个程序为我运行。我正在使用 Python v3.9.1 和 Pandas v1.3.5。
    • @Anthony 我发布了第二种搜索方式,它可能更容易调试,因为它在更多单独的代码行中进行搜索,这可以让您隔离由于更具体的行号而导致的问题.
    • 非常感谢您的帮助!我已经清除了错误,但是现在我想弄清楚为什么我的排除列对于所有行都保持为 0。
    猜你喜欢
    • 2011-06-16
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多