【问题标题】:store dictionary in pandas dataframe在熊猫数据框中存储字典
【发布时间】:2016-09-12 21:07:26
【问题描述】:

我想将字典存储到数据框

dictionary_example={1234:{'choice':0,'choice_set':{0:{'A':100,'B':200,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}},
   234:{'choice':1,'choice_set':0:{'A':100,'B':400},1:{'A':100,'B':300,'C':1000}},
   1876:{'choice':2,'choice_set':0:{'A': 100,'B':400,'C':300},1:{'A':100,'B':300,'C':1000},2:{'A':600,'B':200,'C':100}}
  }

把它们放进去

id choice  0_A  0_B  0_C  1_A  1_B  1_C  2_A  2_B  2_C  
1234  0     100  200 300  200  300  300  500  300  300
234  1      100  400  -   100  300  1000  -    -    -
1876  2     100  400  300  100  300  1000 600 200 100

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    我认为以下非常接近,核心思想是将这些字典转换为 json 并依靠 pandas.read_json 来解析它们。

    dictionary_example={
            "1234":{'choice':0,'choice_set':{0:{'A':100,'B':200,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}},
           "234":{'choice':1,'choice_set':{0:{'A':100,'B':400},1:{'A':100,'B':300,'C':1000}}},
           "1876":{'choice':2,'choice_set':{0:{'A': 100,'B':400,'C':300},1:{'A':100,'B':300,'C':1000},2:{'A':600,'B':200,'C':100}}}
    
        }
    
    df = pd.read_json(json.dumps(dictionary_example)).T
    
    
    def to_s(r):
        return pd.read_json(json.dumps(r)).unstack()
    
    flattened_choice_set = df["choice_set"].apply(to_s)
    
    flattened_choice_set.columns = ['_'.join((str(col[0]), col[1])) for col in flattened_choice_set.columns] 
    
    result = pd.merge(df, flattened_choice_set, 
             left_index=True, right_index=True).drop("choice_set", axis=1)
    
    result
    

    【讨论】:

    • 我用补充的mergestep 编辑了代码,因为没有它我们将丢失“选择”列。我注意到多索引在此过程中被展平为等效的元组。
    • merge之前需要flattened_choice_set.columns = ['_'.join((str(col[0]), col[1])) for col in flattened_choice_set.columns]
    • :) 是的,这是另一种解决方案
    • 有人来看我的新问题吗? stackoverflow.com/questions/39469643/…
    猜你喜欢
    • 2017-01-21
    • 1970-01-01
    • 2018-03-20
    • 2016-10-17
    • 2017-08-02
    • 2017-02-27
    • 2021-07-17
    • 2021-02-15
    • 2015-06-02
    相关资源
    最近更新 更多