Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dictionary of List of Dictionaries to a Pandas Dataframe

I have a dictionary in the structure given below and I need to convert it into a Pandas Dataframe to do some aggregation operations. But I couldn't able to convert it into given output format

{
  "raj": [
    {
      "subject": "science",
      "score": "35",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "40",
      "create_time": "1595980800000"
    }
  ],
  "dev": [
    {
      "subject": "science",
      "score": "23",
      "create_time": "1595990288421"
    }
  ],
  "mag":[
    {
      "subject": "science",
      "score": "41",
      "create_time": "1595990288421"
    },
    {
      "subject": "maths",
      "score": "25",
      "create_time": "1595980800000"
    }
  ]
}

I need the output dataframe to be in the given format

name    subject     score   create_time
------------------------------------------
raj     science     35      1595990288421
raj     maths       40      1595980800000
dev     science     23      1595990288421
mag     science     35      1595990288421
mag     maths       25      1595980800000

Can anyone help me convert the dictionary into required dataframe output ?

like image 369
Dinesh Avatar asked Mar 02 '23 05:03

Dinesh


1 Answers

Using a list comprehension

Ex:

df = pd.DataFrame([{'name': k, ** j} for k, v in data.items() for j in v])
print(df)

Output:

  name  subject score    create_time
0  raj  science    35  1595990288421
1  raj    maths    40  1595980800000
2  dev  science    23  1595990288421
3  mag  science    41  1595990288421
4  mag    maths    25  1595980800000
like image 136
Rakesh Avatar answered May 19 '23 07:05

Rakesh