简体   繁体   English

将字典列表转换为数据帧,其中一列用于键,一列用于值

[英]Convert list of dictionaries to dataframe with one column for keys and one for values

Let's suppose I have the following list: 我们假设我有以下列表:

list1 = [{'a': 1}, {'b': 2}, {'c': 3}]

Which I want to convert it to a panda dataframe that have two columns: one for the keys, and one for the values. 我想将它转换为具有两列的熊猫数据帧:一列用于键,一列用于值。

    keys    values
0    'a'      1
1    'b'      2
2    'c'      3

To do so, I have tried to use pd.DataFrame(list1) and also pd.DataFrame.from_records(list1) , but, in both cases, I get a dataframe like: 为此,我尝试使用pd.DataFrame(list1)pd.DataFrame.from_records(list1) ,但是,在这两种情况下,我得到一个数据帧,如:

     a    b    c
0  1.0  NaN  NaN
1  NaN  2.0  NaN
2  NaN  NaN  3.0

Is there any way to specify what I want? 有什么方法可以指明我想要的吗? By doing research I could only find the way I am describing above. 通过研究,我只能找到我上面描述的方式。

Use list comprehension with flattening for list of tuples: 使用list comprehension与展平元组列表:

df = pd.DataFrame([(i, j) for a in list1 for i, j in a.items()], 
                   columns=['keys','values'])
print (df)
  keys  values
0    a       1
1    b       2
2    c       3

Detail : 细节

print ([(i, j) for a in list1 for i, j in a.items()])

[('a', 1), ('b', 2), ('c', 3)]

If your keys across dictionaries are unique, you can create a single dictionary and feed to pd.DataFrame.from_dict . 如果跨词典的键是唯一的,则可以创建单个词典并输入pd.DataFrame.from_dict This can be facilitated by collections.ChainMap : 这可以通过collections.ChainMap来促进:

from collections import ChainMap

list1 = [{'a': 1}, {'b': 2}, {'c': 3}]

df = pd.DataFrame.from_dict(ChainMap(*list1), orient='index').reset_index()

df.columns = ['key', 'value']

print(df)

  key  value
0   a      1
1   b      2
2   c      3

Alternatively, you can feed directly to pd.DataFrame constructor via a list: 或者,您可以通过列表直接提供给pd.DataFrame构造函数:

df = pd.DataFrame(list(ChainMap(*list1).items()))

虽然@jezrael完全回答了我的问题,但我想指出,如果你将每个字典( {'a':1} )转换为列表( ['a',1] ),你只需要使用pd.DataFrame(list1) ,获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM