如何从给定的数据框架创建嵌套词典?

发布于 2025-02-10 04:07:13 字数 585 浏览 1 评论 0原文

我得到了这样的DF:

level       profile    chest_gold       chest_silver        chest_bronze
1           a          TRUE             FALSE               TRUE
2           a          FALSE            FALSE               TRUE
3           a          FALSE            TRUE                TRUE

我想获得一本用作关键级别和配置文件的字典来返回这样的内容,在1/0中转换了True/False:

d[profile][level] = [1, 0, 1]  #the chest result

例如:

d['a'][1] = [1,0,1]
d['a'][2] = [0,0,1]
d['a'][3] = [0,1,1]

我该怎么做?

PS,如果您留下解决方案,请留下一些评论来解释答案!

I got a df like this one:

level       profile    chest_gold       chest_silver        chest_bronze
1           a          TRUE             FALSE               TRUE
2           a          FALSE            FALSE               TRUE
3           a          FALSE            TRUE                TRUE

I want to obtain a dictionary which uses as key the level and the profile to return something like this, converting the TRUE/FALSE in 1/0:

d[profile][level] = [1, 0, 1]  #the chest result

for example:

d['a'][1] = [1,0,1]
d['a'][2] = [0,0,1]
d['a'][3] = [0,1,1]

How can I do that?

P.s. if you leave a solution please leave also a little comment to explain the answer!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2025-02-17 04:07:13

检查嵌套词典理解。内部理解构建词典,其中键是级别,外部理解构建了一个词典,其中键是剖面。

output = {k: {i: v for i, *v in d.set_index('level').filter(like='chest').astype(int).to_records()} for k, d in df.groupby('profile')}

{'a': {1: [1, 0, 1], 2: [0, 0, 1], 3: [0, 1, 1]}}

Check a nested dictionary comprehension. The inner comprehension builds dictionary where keys are levels and outer comprehension builds a dictionary where the keys are profiles.

output = {k: {i: v for i, *v in d.set_index('level').filter(like='chest').astype(int).to_records()} for k, d in df.groupby('profile')}

{'a': {1: [1, 0, 1], 2: [0, 0, 1], 3: [0, 1, 1]}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文