我已经创建了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
这里我只想从这个数据帧创建嵌套字典
预期产量
{'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]}}
不能有
['xaxis' : 41,'yaxis':42]
,因为它必须是一本字典。我想你是说{"101": {"mapname": "xyz", "data": {"xaxis": 41, "yaxis": 42}}}
可能不是最好的解决方案,但是
似乎有效
相关问题 更多 >
编程相关推荐