Skip to content Skip to sidebar Skip to footer

Pandas Dataframe Created For Each Row

I am attempting to pass data in JSON from an API to a Pandas DataFrame. I could not get pandas.read_json to work with the API data so I'm sure it's not the best solution, but I cur

Solution 1:

You can create list of dictionaries and pass to DataFrame constructor:

L = []
for item in output['data']:
    name = item['name']
    period = item['period']
    value = item['values'][0]['value']

    L.append({'Name': name, 'Period': period, 'Value': value})

df = pd.DataFrame(L)

Or use list comprehension:

L = [({'Name': item['name'], 'Period': item['period'], 'Value': item['values'][0]['value']}) 
       for item in output['data']]

df = pd.DataFrame(L)
print (df)
               Name Period  Value
0  page_video_views    day    634

Sample for testing:

output = {
  "data": [
    {
      "name": "page_video_views",
      "period": "day",
      "values": [
        {
          "value": 634,
          "end_time": "2018-11-23T08:00:00+0000"
        },
        {
          "value": 465,
          "end_time": "2018-11-24T08:00:00+0000"
        }
      ],
      "title": "Daily Total Video Views",
      "description": "Daily: Total number of times videos have been viewed for more than 3 seconds. (Total Count)",
      "id": "{page-id}/insights/page_video_views/day"
    }]}

Solution 2:

Try to convert dictionary after json loading to dataframe like:

output = json.loads(r)
df = pd.DataFrame.from_dict(output , orient='index')
df.reset_index(level=0, inplace=True)

Solution 3:

If you are taking the data from the url. I would suggest this approach and passing only the data stored under an attribute

import request
data=request.get("url here").json('Period')

Period is now dictionary you can now call the pd.DataFrame.from_dict(data) to parse the data

df = pd.DataFrame.from_dict(Period)

Post a Comment for "Pandas Dataframe Created For Each Row"