gpt4 book ai didi

python - 如何将 pandas df 变成带有子组的字典

转载 作者:行者123 更新时间:2023-11-28 22:10:40 26 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:

d = {'country': ['America','America','America','America','Canada','Canada','Canada','Canada'],\
'city': ['New York','New York','San Francisco','San Francisco',u'Montréal',u'Montréal','Toronto','Toronto'],\
'landmark': ['Statue of Liberty', 'Empire State Building','Golden Gate Bridge',\
'Mission District','Biodome', 'Parc Laurier', 'CN Tower', 'Royal Ontario Museum']}
pd.DataFrame(data = d)

我希望它是这样的字典:

all_options = {
'America': {
'New York': ['Statue of Liberty', 'Empire State Building'],
'San Francisco': ['Golden Gate Bridge', 'Mission District'],
},
'Canada': {
u'Montréal': ['Biodome', 'Parc Laurier'],
'Toronto': ['CN Tower', 'Royal Ontario Museum'],
}
}

最佳答案

你可以用 dict comprehension 来做,比如:

all_options = {country: grp.groupby('city')['landmark'].apply(list).to_dict()
for country, grp in df.groupby('country')}

[输出]

{'America': {'New York': ['Statue of Liberty', 'Empire State Building'],
'San Francisco': ['Golden Gate Bridge', 'Mission District']},
'Canada': {'Montréal': ['Biodome', 'Parc Laurier'],
'Toronto': ['CN Tower', 'Royal Ontario Museum']}}

或者,如果您更喜欢更明确的方法,这相当于 for 循环:

all_options = {}

for country, grp in df.groupby('country'):
all_options[country] = grp.groupby('city')['landmark'].apply(list).to_dict()

上面的有用链接包括,DataFrame.groupby , Series.applySeries.to_dict

关于python - 如何将 pandas df 变成带有子组的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439123/

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