Home > Blockchain >  How transform a list of jsons into a dataframe?
How transform a list of jsons into a dataframe?

Time:03-06

I have a list of jsons looking like this:

[
{
'1': [{'code': '7654','location': 'California'}]
},
{
'2': [{'code': '7834','location': 'Texas'},{'code': '3912','location': 'NYC'}]
}
]

I would like to have a pandas dataframe like this:

id value
1  [{'code': '7654','location': 'California'}]
2  [{'code': '7834','location': 'Texas'},{'code': '3912','location': 'NYC'}]

I tried with json normalize but the problem is the keys numbers 1 and 2.

How can I do ?

CodePudding user response:

try,

import pandas as pd

values = [{
    '1': [{'code': '7654', 'location': 'California'}]
}, {
    '2': [{'code': '7834', 'location': 'Texas'}, {'code': '3912', 'location': 'NYC'}]
}]

pd.DataFrame(
    [{"id": k, "value": v} for value in values for k, v in value.items()]
)

  id                                              value
0  1       [{'code': '7654', 'location': 'California'}]
1  2  [{'code': '7834', 'location': 'Texas'}, {'code...
  • Related