gpt4 book ai didi

python - 如何从 pandas 数据帧创建多级嵌套字典?

转载 作者:行者123 更新时间:2023-12-01 00:19:52 29 4
gpt4 key购买 nike

我正在尝试从 pandas 数据帧创建一个多级嵌套字典 - 在下面的示例中,我想检索每个邮政编码、每个性别和年龄组合的工资总和。输出必须是预期输出注释中所示的字典。

from typing import NamedTuple, Sequence, Tuple

import pandas as pd

data = [
["tom", 22, "ab 11", "M", 5555],
["Rob", 22, "ab 11", "M", 9999],
["nick", 33, "ab 22", "M", 3333],
["juli", 18, "ab 11", "F", 2222],
]
people = pd.DataFrame(data, columns=["Name", "Age", "PostalCode", "Sex", "Salary"])

d = (
people.groupby(["PostalCode", "Sex", "Age"])["Salary"]
.apply(sum)
.to_dict()
)

print(d)

# Expected output
print({"ab 11": {("M", 22): 15554, ("F", 18): 2222}, "ab 22": {("M", 33): 3333}})

最佳答案

只需稍微改变你的解决方案并使用额外的字典理解

df = (
people.groupby(["PostalCode", "Sex", "Age"])["Salary"]
.sum()
.unstack(0)
)

d = {col: df[col].dropna().to_dict() for col in df}

print(d)

Out[40]:
{'ab 11': {('F', 18): 2222.0, ('M', 22): 15554.0},
'ab 22': {('M', 33): 3333.0}}

关于python - 如何从 pandas 数据帧创建多级嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59029768/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com