I have a dataframe with 3 columns "ID" , "Date" , "House_Price_Index" and I want to convert this into a dictionary looking like:
{ID:{"Date":"Value" , "House_Price_Index":"Value"}}
Here's a sample of the dataframe:
ID Date House_Price_Index
0 1/1/1975 61.0900
1 1/1/1976 65.5250
2 1/1/1977 73.4350
3 1/1/1978 83.7450
4 1/1/1979 95.1325
5 1/1/1980 102.6675
So the output should be:
{0:{"Date":"1/1/1975","House_Price_Index":"61.0900"}}
... so on and so forth
Thank you very much!
CodePudding user response:
Use DataFrame.to_dict
with convert ID
to index (because column):
d = df.set_index('ID').to_dict('index')
print (d)
{0: {'Date': '1/1/1975', 'House_Price_Index': 61.09},
1: {'Date': '1/1/1976', 'House_Price_Index': 65.525},
2: {'Date': '1/1/1977', 'House_Price_Index': 73.435},
3: {'Date': '1/1/1978', 'House_Price_Index': 83.745},
4: {'Date': '1/1/1979', 'House_Price_Index': 95.1325},
5: {'Date': '1/1/1980', 'House_Price_Index': 102.6675}}