pandas 字典的清单 [英] List of dict of dict in Pandas

查看:44
本文介绍了 pandas 字典的清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的字典列表:

I have list of dict of dicts in the following form:

<代码>[{0:{'city':'newyork','name':'John','age':'30'}},{0:{'city':'newyork','name':'John','age':'30'}},],]

我想以以下形式创建pandas DataFrame:

I want to create pandas DataFrame in the following form:

城市名称年龄纽约约翰30纽约约翰30

尝试了很多但没有成功

你能帮我吗?

推荐答案

结合使用列表理解和 concat

Use list comprehension with concat and DataFrame.from_dict:

L = [{0:{'city':'newyork', 'name':'John', 'age':'30'}},
 {0:{'city':'newyork', 'name':'John', 'age':'30'}}]

df = pd.concat([pd.DataFrame.from_dict(x, orient='index') for x in L])
print (df)
   name age     city
0  John  30  newyork
0  John  30  newyork

具有多个带有新列 id 的键的解决方案应为:

Solution with multiple keys with new column id should be:

L = [{0:{'city':'newyork', 'name':'John', 'age':'30'}, 
      1:{'city':'newyork1', 'name':'John1', 'age':'40'}},
     {0:{'city':'newyork', 'name':'John', 'age':'30'}}]

L1 = [dict(v, id=k) for x in L for k, v in x.items()]
print (L1)
[{'name': 'John', 'age': '30', 'city': 'newyork', 'id': 0}, 
 {'name': 'John1', 'age': '40', 'city': 'newyork1', 'id': 1}, 
 {'name': 'John', 'age': '30', 'city': 'newyork', 'id': 0}]
df = pd.DataFrame(L1)
print (df)
  age      city  id   name
0  30   newyork   0   John
1  40  newyork1   1  John1
2  30   newyork   0   John

这篇关于 pandas 字典的清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆