Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dataframe from dictionary with auto-increment index

I understand to create a dataframe, i need to specify index from my dictionary, else we get the 'ValueError: if using all scalar values, you must pass an index' error.

however, how do i create a dataframe from dictionary where the index is just an auto-increment number?

like image 796
desmond Avatar asked Oct 19 '25 16:10

desmond


2 Answers

You can construct an index using np.arange and pass the len of your dict:

pd.DataFrame(your_dict, index = np.arange(len(your_dict)))

However, if you only have a single value as scalar values in your dict then it's more appropriate to have a single row:

In [165]:
d = {'a':1,'b':3}
pd.DataFrame(d, index=[0])

Out[165]:
   a  b
0  1  3

Or you can use from_dict and pass orient='index':

In [166]:
d = {'a':1,'b':3}
pd.DataFrame.from_dict(d, orient='index')

Out[166]:
   0
a  1
b  3
like image 68
EdChum Avatar answered Oct 21 '25 23:10

EdChum


Two steps

  1. Create a pandas Series from the dictionary ser = pd.Series(dictionary_here)

  2. Create a new dataframe from the Series and it's index as such

    df1 = pd.DataFrame({"column1":ser.index, "column2":ser.values})

like image 30
Tambe Tabitha Avatar answered Oct 21 '25 21:10

Tambe Tabitha