【问题标题】:Transform multi level index dataframe into nested dictionary将多级索引数据框转换为嵌套字典
【发布时间】:2020-07-31 15:15:34
【问题描述】:

我有这个 2 级索引数据框。我想从此数据框创建一个嵌套字典。

                total_prob
SubType Type              
AAA     A>C   7.393806e-07
        A>G   4.823150e-06
        A>T   9.559154e-07
AAC     A>C   6.728159e-07
        A>G   1.772496e-06
        A>T   9.689872e-07
AAG     A>C   1.637682e-06
        A>G   5.986134e-06
        A>T   1.721770e-06

示例输出:

{'AAA':{'A>C': 7.393806e-07, 'A>G': 4.823150e-06, 'A>T': 9.559154e-07}, 'AAC':{'A>C': 6.728159e-07, 'A>G': 1.772496e-06, 'A>T': 9.689872e-07}, 'AAG':{'A>C': 1.637682e-06, 'A>G': 5.986134e-06, 'A>T': 1.721770e-06}

我该怎么做?

【问题讨论】:

    标签: python dataframe dictionary nested


    【解决方案1】:

    试试这个。假设你的数据框是df

    SubType Type  total_prob
    0     AAA  A>C           2
    1     NaN  A>G           3
    2     NaN  A>T           4
    3     AAC  A>C           5
    4     NaN  A>G           6
    5     NaN  A>T           7
    6     AAG  A>C           8
    7     NaN  A>G           9
    8     NaN  A>T          10
    

    你可以ffill用forward方法填充缺失值。下一个groupby并制作json输出。

    df = df.fillna(method="ffill")   
    res = df.groupby(["SubType"]).apply(lambda x: dict(zip(list(x.Type),list(x.total_prob)))).to_json(orient="index")
    

    输出

    '{"AAA":{"A>C":2,"A>G":3,"A>T":4},"AAC":{"A>C":5,"A>G":6,"A>T":7},"AAG":{"A>C":8,"A>G":9,"A>T":10}}'
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2018-08-14
      • 1970-01-01
      • 2017-03-24
      • 2022-01-25
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多