我正在处理一段代码,需要将放置在列表中的多个
NamedTuple
映射起来。
以下是示例代码 - 我主要的问题在于如何映射双重NamedTuple
PeopleName
和PeopleAge
的List
- 我不清楚该如何操作。应该分为两步完成,1 / 将整行提取成通用的NamedTuple
,然后2 / 将记录拆分为不同的NamedTuple
PeopleName
和PeopleAge
。from typing import NamedTuple, List
import pandas as pd
data = [["tom", 10, "ab 11"], ["nick", 15, "ab 22"], ["juli", 14, "ab 11"]]
people = pd.DataFrame(data, columns=["Name", "Age", "PostalCode"])
PeopleName = NamedTuple("PeopleName", [("Name", str)])
PeopleAge = NamedTuple("PeopleAge", [("Age", int)])
PeoplePC = NamedTuple("PeoplePC", [("PostalCode", str)])
# The code below is not correct
Demography = NamedTuple(
"Demography", [("names", List[(PeopleName, PeopleAge)]), ("postalcodes", PeoplePC)],
)
def to_nested_tuple(k, g):
peoples = list(
g["Name"].to_frame().itertuples(name="Person", index=False),
# rec["Age"].to_frame().itertuples(name="PeopleAge", index=False),
)
return Demography(peoples, PeoplePC(k))
d = [to_nested_tuple(*item) for item in people.groupby("PostalCode")]
print(d)