我有pandas数据框 城镇 ,看起来像这样:
**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
答案 0 :(得分:4)
您可以使用groupby
和to_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]]}
答案 1 :(得分:0)
如果您对元组列表没有问题,这是一种方法。假设您的数据框已按ID-cell
排序,并且对于每个城镇,此编号都是唯一的。
from functools import partial
res = df.groupby(['TOWNS'])['NumberOfPopulation']\
.apply(partial(enumerate, start=1))\
.apply(list)\
.to_dict()
print(res)
{'Berlin': [(1, 333)],
'London': [(1, 111), (2, 555)],
'Paris': [(1, 444), (2, 222), (3, 999)]}