【问题标题】:using geopy to find the country name from coordinates in a pandas dataframe使用 geopy 从熊猫数据框中的坐标中查找国家名称
【发布时间】:2016-04-14 12:52:27
【问题描述】:

我正在尝试使用geopy 确定pandas 数据框中每一行的国家/地区名称。我有的是:

import pandas as pd
from geopy.geocoders import GoogleV3

df = pd.DataFrame({'ser_no': [1, 1, 1, 2, 2, 2],
                'lat': [53.57, 35.52, 35.53, 54.66, 54.67, 55.8],
                'lon': [-117.20, -98.29, -98.32, -119.48, -119.47, -119.46]})

def get_country(locations):
    locations = geolocator.reverse(row['lat'], row['lon'], timeout = 10)
    for location in locations:
        for component in location.raw['address_components']:
            if 'country' in component['types']:
                return component['long_name']

my_key = my_api_key                   
geolocator = GoogleV3(my_key, proxies ={"http": 'my proxy',
                                        "https": 'my proxy'})

df['country'] = df.apply(lambda row: get_country(row), axis = 1)

这会返回

     lat     lon  ser_no                                       country
0  53.57 -117.20       1  <function get_country at 0x000000000F6F9C88>
1  35.52  -98.29       1  <function get_country at 0x000000000F6F9C88>
2  35.53  -98.32       1  <function get_country at 0x000000000F6F9C88>
3  54.66 -119.48       2  <function get_country at 0x000000000F6F9C88>
4  54.67 -119.47       2  <function get_country at 0x000000000F6F9C88>
5  55.80 -119.46       2  <function get_country at 0x000000000F6F9C88>

没有发生错误,但我的输出没有用。我不确定它是否只是返回不正确,或者我的apply 有问题。

【问题讨论】:

  • 你的函数签名不应该是row而不是locations吗?
  • get_country(locations) 应该是get_country(row)
  • 改成这样怎么样:df['country'] = df.apply(lambda row: get_country(row), axis = 1) 应该没什么区别,但这里很明确
  • @EdChum 通过将函数参数更改为 row 并明确声明 get_country(row),我得到以下 ValueError: ('Invalid point', u'occurred at index 0')
  • 在哪一行看起来你的错误已经进展了

标签: python pandas dataframe reverse-geocoding geopy


【解决方案1】:

geolocator.reverse 接受一个字符串,因此您需要将函数更改为:

def get_country(row):
    pos = str(row['lat']) + ', ' + str(row['lon'])
    locations = geolocator.reverse(pos, timeout = 10)
    #... rest of func the same

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2022-01-17
    相关资源
    最近更新 更多