在Pandas数据框中存储字典

3
我想把一个字典存储到数据框中。
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
1个回答

4

我认为以下翻译比较接近,核心思想就是将这些字典转换成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

enter image description here


我在代码中添加了一个补充的merge步骤,因为没有它,我们会丢失“choice”列。我注意到在此过程中,多级索引被压缩成其元组等效形式。 - Svend
1
在执行 merge 前,您需要执行 flattened_choice_set.columns = ['_'.join((str(col[0]), col[1])) for col in flattened_choice_set.columns] - jezrael
:) 是的,这是另一种解决方案。 - jezrael
有人能来看看我的新问题吗?http://stackoverflow.com/questions/39469643/store-complex-dictionary-in-pandas-dataframe - GDI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接