python - 从熊猫数据框制作字典
问题描述
我有看起来像这样的熊猫数据框城镇:
**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
解决方案
你可以做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]]}
推荐阅读
- database - 将表重用于预期之外的目的
- python - 如何将 col 拆分为行?
- javascript - JavaScript 简单调用函数行为
- nuxt.js - 使用自定义 vuelidate 函数访问 Nuxt 中的组件方法
- c# - asp.net - 制作通用方法来查找数据库中是否存在实体
- android - Firebase - 已安装的构建工具修订版已损坏
- r - 如何从 terra SpatRaster 构建 lon、lat、value 数据框
- node.js - 在 POST 路由中使用 Express 从 Node 发送文件
- python - 如何在mac上通过python创建文件夹
- css - 媒体查询在普通桌面和响应式设计模式之间无法正常运行,为什么?