Home > Software design >  Convert Embedded JSON Dict To Panda DataFrame Where Columns Headers Are Seperate From Values
Convert Embedded JSON Dict To Panda DataFrame Where Columns Headers Are Seperate From Values

Time:03-09

I'm trying to create a python pandas DataFrame out of a JSON dictionary. The embedding is tripping me up.

The column headers are in a different section of the JSON file to the values.

The json looks similar to below. There is one section of column headers and multiple sections of data.

I need each column filled with the data that relates to it. So value_one in each case will fill the column under header_one and so on.

I have come close, but can't seem to get it to spit out the dataframe as described.

{
  "my_data": {
    "column_headers": [
      "header_one",
      "header_two",
      "header_three"
    ],
    "values": [
      {
        "data": [
          "value_one",
          "value_two",
          "value_three"
        ]
      },
      {
        "data": [
          "value_one",
          "value_two",
          "value_three"
        ]
      }
    ]
  }
}

CodePudding user response:

Assuming your dictionary is my_dict, try:

>>> pd.DataFrame(data=[d["data"] for d in my_dict["my_data"]["values"]],
                 columns=my_dict["my_data"]["column_headers"])
  • Related