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)

3 Answers 3

2

I will using from_records

pd.DataFrame.from_records(d,index='a')
Out[26]: 
   b
a   
1  2
2  3
Sign up to request clarification or add additional context in comments.

Comments

1

How about:

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

2 Comments

What does the index argument in the constructor do? Why can't I create a DataFrame directly with the index column!
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.