I have this data frame:
userId latitude longitude dateTime
0 121165 30.314368 76.384381 2018-02-01 00:01:57
1 95592 13.186810 77.643769 2018-02-01 00:02:17
2 111435 28.512889 77.088154 2018-02-01 00:04:02
3 129532 9.828420 76.310357 2018-02-01 00:06:03
4 95592 13.121986 77.610539 2018-02-01 00:08:54
I want to create a new dataframe column like:
userId latitude longitude dateTime city
0 121165 30.314368 76.384381 2018-02-01 00:01:57 Bengaluru
1 95592 13.186810 77.643769 2018-02-01 00:02:17 Delhi
2 111435 28.512889 77.088154 2018-02-01 00:04:02 Mumbai
3 129532 9.828420 76.310357 2018-02-01 00:06:03 Chennai
4 95592 13.121986 77.610539 2018-02-01 00:08:54 Delhi
I saw this code here, but its not working out.
This is the code given there:
from urllib2 import urlopen
import json
def getplace(lat, lon):
url = "http://maps.googleapis.com/maps/api/geocode/json?"
url += "latlng=%s,%s&sensor=false" % (lat, lon)
v = urlopen(url).read()
j = json.loads(v)
components = j['results'][0]['address_components']
country = town = None
for c in components:
if "country" in c['types']:
country = c['long_name']
if "postal_town" in c['types']:
town = c['long_name']
return town, country
for i,j in df['latitude'], df['longitude']:
getplace(i, j)
I get error at this place:
components = j['results'][0]['address_components']
list index out of range
I put some other latitude longitude values of UK and it worked out, but not for Indian states.
So now I want to try out something like this:
if i,j in zip(range(79,80),range(83,84)):
df['City']='Bengaluru'
elif i,j in zip(range(13,14),range(70,71)):
df['City']='Delhi'
and so on. So how can I assign city in a more feasible manner using latitude and longitude values?