Dictionary to DataFrame | Creating a Pandas DataFrame Using Scalar Values

Trying to make a a Pandas DataFrame from a dictionary but getting the, “If using all scalar values, you must pass an index” error? Have no fear, my crappy work around is here. Let’s just tack on an array element to the dictionary and be on our way! Need to install pip? Checkout out this post.

import pandas as pd
dict = {'one':6,'two':5, 'three':4, 'four':3, 'five':2, 'six':1 }
df = pd.DataFrame().from_dict(dict)

This should recreate the error code. from_dict requires that we define an index or include a non scalar value in our dictionary. Let’s abide and tack on a useless array element.

dict['seven']=[0]
df = pd.DataFrame().from_dict(dict)

Now we can easily create a Pandas DataFrame from our original dictionary. Want to get rid of that random ass column? Pop it out by doing the following.

df.pop('seven')

Now we have what we originally wanted. We could have also just specified the index, but I personally find including an array column easier especially when calling data from APIs. Let’s specify the index just to see how that’s done.

dict = {'one':6,'two':5, 'three':4, 'four':3, 'five':2, 'six':1 }
df = pd.DataFrame(dict, index=[0])

Regardless, both ways are easier than looping through the dictionary and creating the Pandas DataFrame by hand. Happy coding!

Leave a Comment