【问题标题】:Creating a tab separated matrix with placeholders from a dictionary of dictionaries使用字典字典中的占位符创建制表符分隔矩阵
【发布时间】:2015-11-13 22:45:59
【问题描述】:

我有一组 500 个细胞和另一组大约 12 个基因。我还有一本字典,其中包含细胞映射到基因,以及基因映射到计数。我想将此信息构造成一个矩阵,其中我们将单元格作为列名,将基因作为行名。每个基因细胞将包含计数。如果该特定单元格没有计数,则用零占位符填充它

这是一个玩具示例。假设你得到了这些数据:

cells = set(['cell_1', 'cell_2'])
genes = set(['gene_a', 'gene_b', 'gene_c', 'gene_d', 'gene_e', 'gene_f'])
test_data = {'cell_2': {'gene_c': 13, 'gene_f': 6}, 
             'cell_1': {'gene_a': 12, 'gene_c': 2}}

我们想像这样创建一个制表符分隔的表格:

            cell_1| cell_2
    -------|------|-------
    gene_a | 12   | 0
    gene_b | 0    | 0
    gene_c | 2    | 13
    gene_d | 0    | 0
    gene_e | 0    | 0
    gene_f | 0    | 6

这里的最终目标是以制表符分隔的格式写出这个矩阵。任何帮助将不胜感激。

【问题讨论】:

    标签: python dictionary matrix


    【解决方案1】:

    这是一个输出制表符分隔文件的解决方案:

    cells = ['cell_1', 'cell_2']
    genes = ['gene_a', 'gene_b', 'gene_c', 'gene_d', 'gene_e', 'gene_f']
    test_data = {'cell_2': {'gene_c': 13, 'gene_f': 6}, 
                 'cell_1': {'gene_a': 12, 'gene_c': 2}}
    with open("genes.csv", "w") as f:
        f.write("name")
        for cell in cells:
            f.write("\t")
            f.write(cell)
        for gene in genes:
            f.write("\n")
            f.write(gene)
            for cell in cells:
                f.write("\t")
                if cell in test_data and gene in test_data[cell]:
                    val = test_data[cell][gene]
                else:
                    val = 0 # this could be considered an error
                f.write(str(val))
    

    文件如下所示:

    name    cell_1  cell_2
    gene_a  12  0
    gene_b  0   0
    gene_c  2   13
    gene_d  0   0
    gene_e  0   0
    gene_f  0   6
    

    我将细胞和基因保留为列表而不是集合,以保持它们的顺序。列表或集合都没有效率差异,因此如果您已经将它们作为集合也可以。

    我为没有数据的任何细胞/基因输出零,您可能更愿意将其更改为空白或引发错误。

    【讨论】:

      【解决方案2】:

      pythonistic 方式会使用列表推导。此外,将流程分成小步骤使其易于阅读和维护。

      def make_matrix(genes, cells, data):
          return [[data[cell].get(gene, 0) for cell in sorted(cells)] for gene in sorted(genes)]
      
      def add_headers(row_headers, column_headers, matrix):
          annotated_matrix = [[header] + row for header, row in zip(sorted(row_headers), matrix)]
          return [[""] + list(column_headers)] + annotated_matrix
      
      def format_matrix(matrix):
          return '\n'.join(['\t'.join([str(item) for item in row]) for row in matrix])
      
      print(format_matrix(add_headers(genes, cells, make_matrix(genes, cells, test_data))))
      

      还有proof it works

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 2012-08-14
        • 2019-12-15
        • 1970-01-01
        • 2021-09-20
        • 2020-07-10
        相关资源
        最近更新 更多