首页 > 解决方案 > 从熊猫数据框制作字典

问题描述

我有看起来像这样的熊猫数据框城镇:

**towns**
Paris
Berlin
London
etc..

另外,我还有一个数据框totalPopulation看起来像这样:

ID-cell    TOWNS      NumberOfPopulation
1          Paris       444
1          Berlin      333
1          London      111
2          Paris       222
2          London      555
3          Paris       999

我需要使用嵌套列表创建字典,以获得如下内容:

'Paris' : [1, 444],[2,222],[3,999]
'Berlin': [1,333]
'London': [1,111], [2,555]

我试图做这样的事情:

dictionary = {}
for town in towns.itertuples(index = False):
  dictionary[town] = totalPopulation.loc[totalPopulation['TOWNS'] == town].sort_values(totalPopulation.columns[2], ascending=False)

当我在循环之后调用 print 方法时,我得到一个数字列表,我认为是索引。我期待价值。:D

编辑:我只是重新启动计算机(不是因为这个原因:D)并再次运行我的程序。现在我明白了:

{Pandas(town='Paris'): Empty DataFrame
Columns: [ID-cell, TOWNS, NumberOfPopulation]
Index: [], Pandas(Province='London'): Empty DataFrame
Columns: [ID-cell, TOWNS, NumberOfPopulation]
....}

当我尝试

print(dictionary['Paris']) 

我得到 keyError

标签: pythonpython-3.xpandasdictionary

解决方案


你可以做groupbyto_dict

df.groupby('TOWNS')['ID-cell','NumberOfPopulation'].apply(lambda x : x.values.tolist()).get(towns)
{'Berlin': [[1, 333]],
 'London': [[1, 111], [2, 555]],
 'Paris': [[1, 444], [2, 222], [3, 999]]}

推荐阅读