【问题标题】:Error while merging multiple csv with a condition将多个 csv 与条件合并时出错
【发布时间】:2020-03-28 10:56:02
【问题描述】:

要求:我有 69 个 csv。根据以下条件合并它们:

条件:如果标题'col7'的单元格中的值= 1,则将相应的行附加到新的csv中。

你能帮我完成这段代码吗?

下面是我的代码:

with open('merged.csv', 'a') as mergedFile:
    for csv in glob('*.csv'):
        if csv == 'merged.csv':
            pass
        else:
            for line in os.listdir():
                for eachFile in open(csv, 'r'):
                    # write further code here if header 'col7' value = 1
                        # write further code here to add the corresponding rows meeting condition
                        mergedFile.write(line)

如果 pandas 有任何方法可以做到这一点,非常欢迎。

【问题讨论】:

  • csv文件名合并? csv名称的独特之处是什么?另外,你知道你的标题的名字吗?如果你这样做了,csv 模块中的 dict 形式可能会有所帮助
  • 我正在写入的新文件是“merged.csv”。独特的功能在这里无关紧要,这更像是过滤数据。我要过滤的标题名称是'col7'

标签: python python-3.x pandas csv


【解决方案1】:

csv 模块非常适合此任务。您大多只是逐行过滤。 pandas 必须在写入之前将整个 csv 带入内存。

import csv

# todo: do you want append, or use 'w' to start a new file?
with open('merged.csv', 'a', newline='') as mergedFile:
    writer = csv.writer(mergedFile)
    for csvFile in glob('*.csv'): # renamed variable to avoid module name collision
        if csvFile == 'merged.csv':
            continue
        with open(csvFile, newline='') as inFile:
            reader = csv.reader(inFile)
            # assuming there is a header with column names, we are looking for "col7"
            header = next(reader)
            try:
                filterCol = header.index("col7")
            except ValueError as e:
                print("no 'col7' in {}, skipping".format(csvFile))
                continue
            writer.writerows(row for row in reader if row[filterCol == "1")

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2018-05-15
    相关资源
    最近更新 更多