Reputation: 189
I am new to Python and Pandas. I am trying to convert a dictionary to a data frame. My original dictionary is a key followed by uneven length of list. The dict looks as below:
{'PlaceA': [(1992, 2015)], 'PlaceB': [(1980, 1984), (1988, 1991)], 'PlaceC': [(1985, 1987)]}
To convert this to a df, I use
d = pd.DataFrame.from_dict(city_dict, orient='index')
It works fine and produce the resultant df as below:
0 1
PlaceA (1992, 2015) None
PlaceB (1980, 1984) (1988, 1991)
PlaceC (1985, 1987) None
While I can rename column easily using
d.rename(columns={0:'new column name'})
I cannot rename the name of the first column (place name). I tried using
d.rename(columns={'':'place'}, inplace=True)
but it does not work. Strangely, when I tried to print out the header, I get the following output
print(list(d.columns.values))
[0, 1]
Is there anything I am missing out?
Your comments are greatly appreciated!
Thanks
Upvotes: 0
Views: 1149
Reputation: 153510
That first 'column' isn't a column; it is the index. You can name it using:
df.index.name = 'Place Name'
0 1
Place Name
PlaceC (1985, 1987) None
PlaceB (1980, 1984) (1988, 1991)
PlaceA (1992, 2015) None
Or you can convert that index into a column using:
d = d.reset_index()
d.rename(columns={'index':'Place Name'}
Place Name 0 1
0 PlaceC (1985, 1987) None
1 PlaceB (1980, 1984) (1988, 1991)
2 PlaceA (1992, 2015) None
Upvotes: 2