如何从OrderedDicts列表中创建Pandas DataFrame? [英] How to create a Pandas DataFrame from a list of OrderedDicts?

查看:1024
本文介绍了如何从OrderedDicts列表中创建Pandas DataFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表:

o_dict_list = [(OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Coffee')]), 'Ambiguous'),
           (OrderedDict([('StreetNamePreType', 'AVENUE'), ('StreetName', 'Washington')]), 'Ambiguous'),
           (OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Quartz')]), 'Ambiguous')]

就像标题所说的那样,我试图获取此列表并创建一个pandas数据框,其中的列为:'StreetNamePreType''StreetName',并且行包含OrderedDict中每个键的对应值.

And like the title says, I am trying to take this list and create a pandas dataframe where the columns are: 'StreetNamePreType' and 'StreetName' and the rows contain the corresponding values for each key in the OrderedDict.

我已经在StackOverflow上进行了一些搜索,以获取有关如何创建数据框的指导,请参见

I have done some searching on StackOverflow to get some guidance on how to create a dataframe, see here but I am getting an error when I run this code (I am trying to replicate what is going on in that response).

from collections import Counter, OrderedDict
import pandas as pd

col = Counter()
for k in o_dict_list:
    col.update(k)

df = pd.DataFrame([k.values() for k in o_dict_list], columns = col.keys())

运行此代码时,出现的错误是:TypeError: unhashable type: 'OrderedDict'

When I run this code, the error I get is: TypeError: unhashable type: 'OrderedDict'

我在此处查找了此错误,发现数据类型,但不幸的是,我对Python/Pandas的内部运作方法了解不足,无法独自解决此问题.

I looked up this error, here, I get that there is a problem with the datatypes, but I, unfortunately, I don't know enough about the inner workings of Python/Pandas to resolve this problem on my own.

我怀疑我的OrderedDict列表与此处不完全相同这就是为什么我的代码无法正常工作的原因.更具体地说,我相信我有一个集合列表,每个元素都包含一个OrderedDict.我链接到此处的示例似乎是真实的列表OrderedDicts.

I suspect that my list of OrderedDict is not exactly the same as in here which is why I am not getting my code to work. More specifically, I believe I have a list of sets, and each element contains an OrderedDict. The example, that I have linked to here seems to be a true list of OrderedDicts.

同样,我对Python/Pandas的内部运作方法了解不足,无法独自解决此问题,并正在寻求帮助.

Again, I don't know enough about the inner workings of Python/Pandas to resolve this problem on my own and am looking for help.

推荐答案

我将使用列表理解来做到这一点,如下所示.

I would use list comprehension to do this as follows.

pd.DataFrame([o_dict_list[i][0] for i, j in enumerate(o_dict_list)])

请参见下面的输出.

See the output below.

 StreetNamePreType  StreetName
0   ROAD            Coffee
1   AVENUE          Washington
2   ROAD            Quartz

这篇关于如何从OrderedDicts列表中创建Pandas DataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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