如何将嵌套字典转换为pandas数据框?

炸薯条

我有这个嵌套的字典:

{'attrs': ('LA', 'E', 'Can', 'AP', 'ME', 'A', 'M', 'Car', 'US'),
 'self': {'ac': {'AP', 'Can', 'Car', 'E', 'LA', 'M', 'ME', 'US'},
  'anz': {'AP', 'E', 'US'},
  'ana': {'AP', 'E', 'US'},
  'aa': {'AP'},
  'taag': {'A', 'AP', 'Can', 'E', 'ME', 'US'},
  'bm': {'E'},
  'l': {'A', 'AP', 'Can', 'E', 'LA', 'M', 'ME', 'US'},
  'm': {'Can', 'Car', 'LA', 'M', 'US'},
  'sca': {'A', 'AP', 'E', 'LA', 'US'},
  'sia': {'A', 'AP', 'Can', 'E', 'ME', 'US'},
  'tai': {'AP', 'Car', 'E', 'LA', 'US'},
  'ua': {'AP', 'Can', 'Car', 'E', 'LA', 'M', 'US'},
  'v': {'A', 'AP', 'E', 'LA', 'M', 'US'}}}

这就是我的构建方式:

build_context = lambda objects, attributes, table : {'attrs' : tuple(attributes), 'self' : {object : {attributes[i] for i in range(len(row)) if row[i]} for (object, row) in zip(objects, table)}}


context = build_context(objects =
('ac', 'anz', 'ana', 'aa', 'taag', 'bm', 'l', 'm', 'sca', 'sia', 'tai',
'ua', 'v'),
attributes = ('LA', 'E', 'Can', 'AP', 'ME', 'A', 'M', 'Car', 'US'),
table = ((True,True,True,True,True,False,True,True,True),
(False,True,False,True,False,False,False,False,True), (False,True,False,True,False,False,False,False,True),
(False,False,False,True,False,False,False,False,False),
(False,True,True,True,True,True,False,False,True),
(False,True,False,False,False,False,False,False,False),
(True,True,True,True,True,True,True,False,True),
(True,False,True,False,False,False,True,True,True), (True,True,False,True,False,True,False,False,True),
(False,True,True,True,True,True,False,False,True),
(True,True,False,True,False,False,False,True,True),
(True,True,True,True,False,False,True,True,True),
(True,True,False,True,False,True,True,False,True)))

如何将其转换为熊猫数据框?它应该看起来像这样,但是我在代码中使用了缩写:

在此处输入图片说明

贝尼

让我们试着explodecrosstab

s = pd.Series(d['self']).apply(list).explode()
out = pd.crosstab(s.index,s).reindex(columns=d['attrs'],fill_value=0)
out =out.rename_axis(None).rename_axis(None,axis=1).reset_index().rename(columns={'index':'company'})
Out[193]: 
   company  LA  E  Can  AP  ME  A  M  Car  US
0       aa   0  0    0   1   0  0  0    0   0
1       ac   1  1    1   1   1  0  1    1   1
2      ana   0  1    0   1   0  0  0    0   1
3      anz   0  1    0   1   0  0  0    0   1
4       bm   0  1    0   0   0  0  0    0   0
5        l   1  1    1   1   1  1  1    0   1
6        m   1  0    1   0   0  0  1    1   1
7      sca   1  1    0   1   0  1  0    0   1
8      sia   0  1    1   1   1  1  0    0   1
9     taag   0  1    1   1   1  1  0    0   1
10     tai   1  1    0   1   0  0  0    1   1
11      ua   1  1    1   1   0  0  1    1   1
12       v   1  1    0   1   0  1  1    0   1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章