Do not use keys in dictionary as index when converting to dataframe using pandas from_dict

Viewed 2074
odict = OrderedDict([ ('dub', ['8084', 'command']),
      ('lhr',['8083','command']),
      ('ams',['8085','command']),])

df = pandas.DataFrame.from_dict(odict, orient='index')
print(df)

I have the above OrderedDict and command to convert to dataframe. I would like the keys in the dict to be used as data in a column rather than being used as the index. It's printing out like this below.

        0        1
dub  8084  command
lhr  8083  command
ams  8085  command

However I would like it to print like this using what I think is called RangeIndex.

    0     1        2
0 dub  8084  command
1 lhr  8083  command
2 ams  8085  command
1 Answers

Use DataFrame.reset_index for RangeIndex and then create default columns names by np.arange:

df = pd.DataFrame.from_dict(odict, orient='index').reset_index()
df.columns = np.arange(len(df.columns))
print(df)
     0     1        2
0  dub  8084  command
1  lhr  8083  command
2  ams  8085  command

Another solution with list comprehension:

df = pd.DataFrame([(k, *v) for k, v in odict.items()])
print(df)
     0     1        2
0  dub  8084  command
1  lhr  8083  command
2  ams  8085  command
Related