Home > Software design >  Convert a single column dataframe into an array/list of dictionaries in python
Convert a single column dataframe into an array/list of dictionaries in python

Time:02-23

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
    }
]

CodePudding user response:

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}]

CodePudding user response:

df.to_dict('records')

This is what you are looking for
Important: parameter is 'records' and not 'record'

CodePudding user response:

You can use to_dict with records(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html)

df.to_dict('records')

CodePudding user response:

Here you go

import pandas as pd

df = pd.DataFrame({'score': [10.4, 22.4, 36.2]}, 
                  index = [1645401600.0, 1645405200.0, 1645408800.0])
df = df.rename_axis('timestamp').reset_index()
df = df.to_dict('records')

Output

>>> [{'timestamp': 1645401600.0, 'score': 10.4}, 
     {'timestamp': 1645405200.0, 'score': 22.4}, 
     {'timestamp': 1645408800.0, 'score': 36.2}]
  • Related