0

I have a list of dictionaries that look like this.

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

I am trying to construct a DataFrame from this as follows:

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

But I get this error:

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

(X is a number of items I have in d)

Aditya
  • 1,240
  • 2
  • 14
  • 38

3 Answers3

2

I will using from_records

pd.DataFrame.from_records(d,index='a')
Out[26]: 
   b
a   
1  2
2  3
BENY
  • 317,841
  • 20
  • 164
  • 234
1

How about:

df = pd.DataFrame(d).set_index('a')
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • What does the index argument in the constructor do? Why can't I create a DataFrame directly with the index column! – Aditya May 06 '19 at 17:07
  • The index argument in the constructer expects a list or series. In other words it expects all index values to be provided as a list. You could use the index argument but you would need to traverse your list of dictionaries to gather the index values in the form of a list to do so. i.e. pd.DataFrame.from_records(d,index=[record['a'] for record in d]) May as well just let pandas ingest the list of dictionaries as records then assign one of the columns as the index. – Michael Bridges Apr 01 '22 at 00:00
1

Because I cannot comment. See here Convert list of dictionaries to a pandas DataFrame

And Quang Hoang is correct. This is analogous to timeseries data. You want to set the index after the dataframe has been built.

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

The index argument in the constructor expects a list or a series so setting it as 'a' will mean there is only 1 row. However setting the index to the column 'a' after the dataframe has been built, sets the index to the series represented by the column 'a'. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

Michael Bridges
  • 351
  • 2
  • 6