我正在尝试从CSV创建用于国家/地区地理位置的列。
到目前为止,我可以同时创建两个新列,latitude
并且可以longitude
在列上进行映射并应用geolocate()
函数。
数据框
geolocation
(-34.9964963, -64.9672817)
预期产量:
geolocation latitude longitude
(-34.9964963, -64.9672817) -34.9964963 -64.9672817
我正在对列进行映射,所以我不确定如何获取经度和纬度并分别创建列。
def add_geolocation(df, country_column):
df["geolocation"] = country_column.map(lambda x: geolocate(x))
return df
add_geolocation(df=df, country_column=df["country"])
在函数中,geolocate()
我将它们都返回。
def geolocate(country):
# Location
loc = geolocator.geocode(country, timeout=10000)
# Latitiude
lat = get_latitude(loc)
# Longitude
long_ = get_longitude(loc)
# Address
add = get_address(loc)
return lat, long_
我可以在lambda函数中指定只使用纬度。
例如,latitude, longitude = geolocate(country)
然后只使用纬度值即可。
您可以zip
用来解压缩geolocation
列内的元组:
def add_geolocation(df, country_column):
df["geolocation"] = country_column.map(geolocate)
df['lat'], df['long'] = zip(*df['geolocation'])
return df
编辑:怎么zip(*df['geolocation'])
办?这是两个不同概念的组合:star(*
)运算符和zip
函数。
该*
运营商解包收集到的位置参数。以下两个调用是等效的:
def f(a, b):
return a + b
f(1, 2) # return 3
lst = [1,2]
f(*lst) # return 3
该zip
函数成对返回输入集合中的元素:
zip([1,2], ['A', 'B'], ['One', 'Two']) # return (1, 'A', 'One'), (2, 'B', 'Two')
我们在这里将两者结合起来,将geolocation
元组的第一个元素拆分为一个单独的集合,然后将第二个元素拆分为另一个集合:
geolocation
(1,2)
(3,4)
(5,6)
zip(*df['geolocation']) == zip((1,2), (3,4), (5,6)) == [(1,3,5), (2,4,6)]
# The first is a collection of latitudes, second is longitudes
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句