Link to home
Start Free TrialLog in
Avatar of crompnk
crompnkFlag for United Kingdom of Great Britain and Northern Ireland

asked on

TypeError: 'float' object is not subscriptable

Hi,

Using Python I'm trying to read a json string and output it to a dataframe, but I get the following error:

TypeError: 'float' object is not subscriptable

code is here:
# We import the requests module which allows us to make the API call
import pandas as pd
import ast
import json
import requests

# Call API to pull data
url = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22'

response = requests.get(url = url)
response_data = response.json()

#data = response_data

data = """{  
   'coord':{  
      'lon':-0.13,
      'lat':51.51
   },
   'weather':[  
      {  
         'id':300,
         'main':'Drizzle',
         'description':'light intensity drizzle',
         'icon':'09d'
      }
   ],
   'base':'stations',
   'main':{  
      'temp':280.32,
      'pressure':1012,
      'humidity':81,
      'temp_min':279.15,
      'temp_max':281.15
   },
   'visibility':10000,
   'wind':{  
      'speed':4.1,
      'deg':80
   },
   'clouds':{  
      'all':90
   },
   'dt':1485789600,
   'sys':{  
      'type':1,
      'id':5091,
      'message':0.0103,
      'country':'GB',
      'sunrise':1485762037,
      'sunset':1485794875
   },
   'id':2643743,
   'name':'London',
   'cod':200
}"""

val = ast.literal_eval(data)
val1 = json.loads(json.dumps(val))
val2 = val1['main']['temp'][0]
dataset = pd.DataFrame(val2)
#OutputDataSet=dataset
#print(val1)
print(dataset)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of crompnk

ASKER

This worked:

import pandas as pd
import json
import requests


# In[2]:


data = {  
   'coord':{  
      'lon':-0.13,
      'lat':51.51
   },
   'weather':[  
      {  
         'id':300,
         'main':'Drizzle',
         'description':'light intensity drizzle',
         'icon':'09d'
      }
   ],
   'base':'stations',
   'main':{  
      'temp':280.32,
      'pressure':1012,
      'humidity':81,
      'temp_min':279.15,
      'temp_max':281.15
   },
   'visibility':10000,
   'wind':{  
      'speed':4.1,
      'deg':80
   },
   'clouds':{  
      'all':90
   },
   'dt':1485789600,
   'sys':{  
      'type':1,
      'id':5091,
      'message':0.0103,
      'country':'GB',
      'sunrise':1485762037,
      'sunset':1485794875
   },
   'id':2643743,
   'name':'London',
   'cod':200
}


# In[6]:


val = json.loads(json.dumps(data))


# In[19]:


val1 = val['main']


# In[32]:


df = pd.DataFrame(list(val1.items()), index=[1, 2, 3, 4, 5])
df

Open in new window