熊猫从带有索引列的词典列表中创建一个DataFrame

时间:2019-05-06 17:04:44

标签: python pandas

我有一个像这样的字典列表。

d = [{'a': 1, 'b': 2}, {'a': 2, 'b': 3}....]

我正在尝试以此方式构造一个DataFrame:

df = pd.DataFrame(d, index=['a'])

但是我得到这个错误:

ValueError: Shape of passed values is (X, 2), indices imply (1, 2)

(X是我在d中拥有的许多物品)

3 个答案:

答案 0 :(得分:2)

我将使用from_records

pd.DataFrame.from_records(d,index='a')
Out[26]: 
   b
a   
1  2
2  3

答案 1 :(得分:1)

怎么样:

Main inherits from DLL-DB.
Worker-DLL inherits from DLL-DB.
Main dynamically loads n-Worker(s)

答案 2 :(得分:1)

因为我无法发表评论。在这里Convert list of dictionaries to a pandas DataFrame

广煌是正确的。这类似于时间序列数据。您要在建立数据框后设置索引。

df = pd.DataFrame(d).set_index('a')

构造函数中的index参数需要一个列表或一系列,因此将其设置为“ a”将意味着只有1行。但是,在建立数据帧之后将索引设置为列“ a”,则将索引设置为由列“ a”表示的序列。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html