【问题标题】:python; merge dictionaries with each dictionary in a new column of the output csv filePython;将字典与输出 csv 文件的新列中的每个字典合并
【发布时间】:2017-09-15 11:04:05
【问题描述】:

使用以下脚本,我将 3 个文件解析为 Python 中的一个字典。字典没有所有相似的键,我希望输出 csv 文件的新列中的每个字典的值。因此,键必须全部在一列中,然后是每列包含不同字典的值的列。 我的脚本的问题是仅在存在值时才附加值,结果是不同字典的值被放置在输出 csv 文件的错误列中。 我的脚本如下:

  def get_file_values(find_files, output_name):
        for root, dirs, files in os.walk(os.getcwd()):
            if all(x in files for x in find_files):
                outputs = []
                for f in find_files:
                    d = {}
                    with open(os.path.join(root, f), 'r') as f1:
                        for line in f1:
                            ta = line.split()
                            d[ta[1]] = int(ta[0])
                    outputs.append(d)

                d3 = defaultdict(list)
                for k, v in chain(*(d.items() for d in outputs)):
                    d3[k].append(v)

                with open(os.path.join(root, output_name), 'w+', newline='') as fnew:
                    writer = csv.writer(fnew)
                    writer.writerow(["genome", "contig", "genes", "SCM", "plasmidgenes"])
                    for k, v in d3.items():
                        fnew.write(os.path.basename(root) + ',')
                        writer.writerow([k] + v)
                        print(d3)

    get_file_values(['genes.faa.genespercontig.csv', 'hmmer.analyze.txt.results.txt', 'genes.fna.blast_dbplasmid.out'], 'output_contigs_SCMgenes.csv')

我现在的输出是:

genome contig  genes   SCM     plasmidgenes
Linda     9     359     295    42
Linda     42    1       2      
Linda     73    29      5   
Linda     43    17      6   
Linda     74    4       
Linda     48    11      
Linda     66    27      

我想拥有它;

genome contig  genes   SCM     plasmidgenes
Linda     9     359     295    42
Linda     42    1       2      0
Linda     73    0       29     5    
Linda     43    17      0      6    
Linda     74    0       0      4        
Linda     48    0       11     0    
Linda     66    27      0      0

【问题讨论】:

  • 嘿。您是否必须出于某些特定原因使用字典?因为使用 pandas Series 和 Dataframes 会更适合这项工作。
  • 我从未使用过数据框,但我也可以使用它。你能帮我重写熊猫的脚本吗?输入文件与您期望的相反:首先是值,然后是键(用空格分隔)。因此,我认为字典会是一个不错的选择。
  • 我当然可以帮忙。但首先,我在可视化您的输入时遇到了一些麻烦。您可以发布文件 1 的内容来帮助我吗?我猜是这样的:Linda 基因组 \n 9 contig \n 359 个基因 \n 295 SCM \n 42 个质粒基因 \n
  • 我已经在一个新问题中发布了我拥有和需要的内容,因为在那里我可以显示我的文件等。新问题是; stackoverflow.com/questions/43738909/…

标签: python csv dictionary append


【解决方案1】:

最简单的解决方法:检查该值是否存在,如果确实附加它,则将 0 附加到您的数据数组。

可能是更复杂的解决方法:使用不同的数据结构,例如 Pandas 或类似于您的数据的二维数组。

二维数组示例:

您将首先遍历文件并用d3[lineNumber][key] 填充d3 数组。例如d3[0]['genome'] 将是您的第一行第一列。

那么你应该可以输出带有以下块的文件:

with open(os.path.join(root, output_name), 'w+', newline='') as fnew:
    writer = csv.writer(fnew)

    # write header row
    header = ""
    for k, v in d3[0].items():
        header += k + ','
    writer.writerow(header)

    # write data rows
    for key, row in d3.items():
        line = ""
        line += os.path.basename(root)
        for k, v in row.items():
            line += ',' + v
        writer.writerow(line)

【讨论】:

    猜你喜欢
    • 2022-12-08
    • 1970-01-01
    • 2019-05-16
    • 2014-07-28
    • 1970-01-01
    • 2022-01-19
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多