'Convert a single column dataframe into an array/list of dictionaries in python
My dataframe is as shown:
score
timestamp
1645401600.0 10.4
1645405200.0 22.4
1645408800.0 36.2
I want to convert it to an array of dictionaries. Expected Result is :
result=[
{
timestamp:1645401600.0
score:10.4
},
{
timestamp:1645405200.0
score:22.4
},
{
timestamp:1645408800.0
score:36.2
}
]
Solution 1:[1]
Reset the index and then use to_dict:
result = df.reset_index().to_dict('records')
Output:
>>> result
[{'timestamp': 1645401600.0, 'score': 10.4},
{'timestamp': 1645405200.0, 'score': 22.4},
{'timestamp': 1645408800.0, 'score': 36.2}]
Solution 2:[2]
df.to_dict('records')
This is what you are looking for
Important: parameter is 'records' and not 'record'
Solution 3:[3]
You can use to_dict with records(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html)
df.to_dict('records')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ujjwal Kumar Maharana |
| Solution 3 |
