简体   繁体   English

如何将 dataframe 转换为嵌套字典?

[英]How to convert dataframe to nested dictionary?

I am running Python 3.7 and Pandas 1.1.3 and have a DataFrame which looks like this:我正在运行 Python 3.7 和 Pandas 1.1.3 并有一个 DataFrame 看起来像这样:

location = {'city_id': [22000,25000,27000,35000],
        'population': [3971883,2720546,667137,1323],
        'region_name': ['California','Illinois','Massachusetts','Georgia'],
        'city_name': ['Los Angeles','Chicago','Boston','Boston'],
        }

df = pd.DataFrame(location, columns = ['city_id', 'population','region_name', 'city_name'])

I want to transform this dataframe into a dict that looks like:我想将此 dataframe 转换为如下所示的字典:

{
'Boston': {'Massachusetts': 27000, 'Georgia': 35000},
 'Chicago': {'Illinois': 25000},
 'Los Angeles': {'California': 22000}
}

And if the same cities in different regions, nested JSON should be sorted by population (for example Boston is in Massachusetts and Georgia. The city in Massachusetts is bigger, we output it first.而如果同一个城市在不同地区,嵌套的JSON应该按人口排序(比如波士顿在马萨诸塞州和乔治亚州。马萨诸塞州的城市比较大,我们先output吧。

My code is:我的代码是:

result = df = df.groupby(['city_name'])[['region_name','city_id']].apply(lambda x: x.set_index('region_name').to_dict()).to_dict()

Output: Output:

{'Boston': {'city_id': {'Massachusetts': 27000, 'Georgia': 35000}},
 'Chicago': {'city_id': {'Illinois': 25000}},
 'Los Angeles': {'city_id': {'California': 22000}}}

how can you see to dictionary add key - "city_id"你怎么能看到字典添加键 - “city_id”

Tell me, please, how I should change my code that gets the expected result?请告诉我,我应该如何更改获得预期结果的代码?

just method chain apply() method to your current solution:只是方法链apply()方法到您当前的解决方案:

result=df.groupby(['city_name'])[['region_name','city_id']].apply(lambda x: x.set_index('region_name').to_dict()).apply(lambda x:list(x.values())[0]).to_dict()

Now if you print result you will get your expected output:现在,如果您打印result ,您将获得预期的 output:

{'Boston': {'Massachusetts': 27000, 'Georgia': 35000},
 'Chicago': {'Illinois': 25000},
 'Los Angeles': {'California': 22000}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM