Python:嵌套字典

2024-09-28 22:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了DataFrame,请检查下面的代码段

data = {'mapid': [101,102],
        'mapname': ['xyz','xyy'],
        'xaxis' : [41,42],
        'yaxis' : [42,32]
        }
        
df = pd.DataFrame(data, columns = ['mapid', 'mapname','xaxis','yaxis'])```

Output of Dataframe.

``print(df)

mapid mapname  xaxis  yaxis
101     xyz     41     42
102     xyy     42     32

这里我只想从这个数据帧创建嵌套字典

预期产量

enter image description here

{'101':{'mapname':'xyz'
            'data' : ['xaxis' : 41,'yaxis':42]}}

我尝试了下面的代码,得到了预期的输出,但我仍然无法理解。请帮帮我

#Tried Snippet
**code**

print({n: grp.loc[n].to_dict('index')for n, grp in df.set_index(['mapid', 'mapname']).groupby(level='mapid')})

**output**

{101: {'xyz': {'xaxis': 41, 'yaxis': 42}}, 102: {'xyy': {'xaxis': 42, 'yaxis': 32}}}

**code**

print({k:f.groupby('mapname')['xaxis'].apply(list).to_dict() for k, f in df.groupby('mapid')})

**output**

{101: {'xyz': [41]}, 102: {'xyy': [42]}}

Tags: todataframedfdatacodedictprintgroupby
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:40

不能有['xaxis' : 41,'yaxis':42],因为它必须是一本字典。我想你是说 {"101": {"mapname": "xyz", "data": {"xaxis": 41, "yaxis": 42}}}

可能不是最好的解决方案,但是

{i:{"mapname": j,"data":k} for (i,j),k in df.set_index(["mapid","mapname"]).to_dict(orient="index").items()}

似乎有效

相关问题 更多 >