[英]Add latitude and longitude column to existing data frame
I am unable to add latitude and longitude column to existing data frame.我无法将纬度和经度列添加到现有数据框中。 I have extracted coordinates from one of the column Restaurant_Location from my data-set using below code.我已使用以下代码从我的数据集中的Restaurant_Location列之一提取坐标。
location = [x for x in rest_df['Restaurant_Location'].unique().tolist() if type(x) == str]
latitude = []
longitude = []
for i in range(0, len(location)):
if(type(location[i]) == str):
ctr=0
while True:
try:
address = location[i] + ', Mumbai, India'
geolocator = Nominatim(user_agent="ny_explorer")
loc = geolocator.geocode(address)
latitude.append(loc.latitude)
longitude.append(loc.longitude)
print('The geographical coordinate of location are {}, {}.'.format(loc.latitude, loc.longitude))
except:
ctr+=1
if(ctr==7):
print(i)
latitude.append(address)
longitude.append(address)
break
continue
break
I am able to get the desired Output我能够得到所需的Output
The geographical coordinate of location are 19.1840129, 72.8412155.
The geographical coordinate of location are 19.0583358, 72.8302669.
But after running above code successfully rest_df.head()
is not showing location_latitude & location_longitude columns in my data-frame, which I want to add in the data-frame.但是在成功运行上面的代码之后, rest_df.head()
没有在我的数据框中显示location_latitude和location_longitude列,我想在数据框中添加它们。 Also there are several other columns in my data-frame.我的数据框中还有其他几列。 Please let me know where I am doing mistake?请让我知道我在哪里做错了?
Here is a pice of code that should work, I deleted some stuff as I'm not sure why, but you can still put them back if you do other things in it.这是一段应该可以工作的代码,我不知道为什么删除了一些东西,但是如果你在其中做其他事情,你仍然可以把它们放回去。 new_df
should have all the rows from your original dataframe, and added the two columns you want. new_df
应该包含原始 dataframe 中的所有行,并添加了您想要的两列。 I have not been able to test as I don't have your data, so they might have typo but the idea is there我无法测试,因为我没有你的数据,所以他们可能有错字,但想法就在那里
location = [x for x in rest_df['Restaurant_Location'].unique().tolist()
if type(x) == str]
latitude = []
longitude = []
for i in range(0, len(location)):
# remove things that does not seem usefull here
try:
address = location[i] + ', Mumbai, India'
geolocator = Nominatim(user_agent="ny_explorer")
loc = geolocator.geocode(address)
latitude.append(loc.latitude)
longitude.append(loc.longitude)
print('The geographical coordinate of location are {}, {}.'.format(loc.latitude, loc.longitude))
except:
# in the case the geolocator does not work, then add nan element to list
# to keep the right size
latitude.append(np.nan)
longitude.append(np.nan)
# create a dataframe with the locatio, latitude and longitude
df_ = pd.DataFrame({'Restaurant_Location':location,
'location_latitude': latitude,
'location_longitude':longitude})
# merge on Restaurant_Location with rest_df to get the column
new_df = rest_df.merge(df_, on='Restaurant_Location', how='left')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.