简体   繁体   English

当字典值为列表时,如何在 Python 中将字典转换为 pandas DataFrame?

[英]How to convert dictionary to pandas DataFrame in Python when dictionary value is a List?

I want to convert Python dictionary into DataFrame.我想将 Python 字典转换为 DataFrame。 Dictionary value is a List with different length.字典值是一个不同长度的列表。

Example:例子:

import pandas as pd

data = {'A': [1], 'B': [1,2], 'C': [1,2,3]}

df = pd.DataFrame.from_dict(data)

But, the above code doesn't work with the following error:但是,上面的代码不适用于以下错误:

ValueError: All arrays must be of the same length

The output that I would like to get is as follows:我想得到的output如下:

name    value    
'A'      [1]         
'B'      [1,2]
'C'      [1,2,3] 
  

You can use:您可以使用:

df = pd.DataFrame({'name':data.keys(), 'value':data.values()})
print (df)
  name      value
0    A        [1]
1    B     [1, 2]
2    C  [1, 2, 3]

df = pd.DataFrame(data.items(), columns=['name','value'])
print (df)
  name      value
0    A        [1]
1    B     [1, 2]
2    C  [1, 2, 3]

Also working Series:也在工作系列:

s = pd.Series(data)

print (s)
A          [1]
B       [1, 2]
C    [1, 2, 3]
dtype: object

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

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