[英]Problem with trailing zeros after converting a pandas column to astype(str)
[英]Converting a column with address and coordinates to string with .astype(str) drops the coordinates
我正在使用geopy包搜索其坐標的地址,該列返回匹配的地址和坐標
我只想獲取坐標
這是一個測試,向您展示其工作方式:
# Test to see if response is obtained for easy address
location = geolocator.geocode("175 5th Avenue NYC", timeout=10)
print((location.latitude, location.longitude))
>>> (40.7410861, -73.9896298241625)
在我的代碼中,我有一個包含城市的CSV,然后使用geopy包進行查找
data['geocode_result'] = [geolocator.geocode(x, timeout = 60) for x in data['ghana_city']]
我只想從這里得到坐標
盡管正則表達式很好,但使用extract似乎無效,並且僅返回NaN值:
p = r'(?P<latitude>-?\d+\.\d+)?(?P<longitude>-?\d+\.\d+)'
data[['g_latitude', 'g_longitude']] = data['geocode_result2'].str.extract(p, expand=True)
data
我感覺這些問題是由於列中的geopy返回的對象引起的
經Regexr.com驗證,正則表達式是正確的:
我曾嘗試將列轉換為字符串, 但是坐標已刪除?
data['geocode_result2'] = (data['geocode_result2']).astype(str)
data
有人可以幫忙嗎? 非常感謝
虛擬數據:
我要從中提取坐標的列是geocode_result2或geocode_result
geocode_result2
1 (Agona Swedru, Central Region, Ghana, (5.534454, -0.700763))
2 (Madina, Adenta, Greater Accra Region, PMB 107 MD, Ghana, (5.6864962, -0.1677052))
3 (Ashaiman, Greater Accra Region, TM3 8AA, Ghana, (5.77329565, -0.110766330148484))
獲得坐標的最終代碼:
data['geocode_result'] = [geolocator.geocode(x, timeout = 60) for x in data['ghana_city']]
x = data['geocode_result']
data.dropna(subset=['geocode_result'], inplace=True)
data['g_latitude'] = data['geocode_result'].apply(lambda loc: loc.latitude)
data['g_longitude'] = data['geocode_result'].apply(lambda loc: loc.longitude)
data
您可以嘗試使用.apply
和.str
例如:
def getLatLog(d):
try:
return re.findall(r"\d+\.\d+", d)
except:
return [None, None]
df['g_latitude'], df['g_longitude'] = df["geocode_result2"].apply(lambda x: getLatLog(x)).str
print(df["g_latitude"])
print(df["g_longitude"])
輸出:
0 5.534454
1 5.6864962
2 5.77329565
Name: g_latitude, dtype: object
0 0.700763
1 0.1677052
2 0.110766330148484
Name: g_longitude, dtype: object
geolocator.geocode
返回Location
對象而不是字符串(盡管其字符串表示形式實際上包含您嘗試解析的經/緯度),因此可以分別通過訪問location.latitude
/ location.longitude
屬性來檢索經/緯度。
# Make geocoding requests
data['geocode_result'] = [geolocator.geocode(x, timeout = 60) for x in data['ghana_city']]
# Extract lat/long to separate columns
data['g_latitude'] = data['geocode_result'].apply(lambda loc: loc.latitude)
data['g_longitude'] = data['geocode_result'].apply(lambda loc: loc.longitude)
(由於缺乏聲譽,我無法發表評論,因此我在這里回答坐標下降的混亂情況)。
str(location)
返回文本地址(不帶坐標),但是repr(location)
返回以下格式的字符串(包括坐標):
Location(%(address)s, (%(latitude)s, %(longitude)s, %(altitude)s))
打印data
時看到的內容使用了repr
(為了簡潔起見,熊貓似乎刪除了領先的Location
類型),因此可以看到坐標。 但是,當列轉換為str
,它將使用str
表示形式,其中不包括坐標。 這就是整個魔術。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.