如何使用geopy从坐标获取邮政编码?

时间:2017-12-15 02:20:25

标签: python pandas numpy geolocation geopy

以下是我一直在使用的代码。我有点新手。由于使用API​​的配额,我一直在测试数据的负责人。以下是数据帧的快照:

        latitude    longitude
0   -73.99107       40.730054
1   -74.000193      40.718803
2   -73.983849      40.761728
3   -73.97499915    40.68086214
4   -73.89488591    40.66471445

这是我被绊倒的地方。

train['latlng'] = train.apply(lambda row: '{},{}'.format(row['latitude'], 
row['longitude']), axis=1)
train['geocode_data'] = train['latlng'].map(reverse_geocode)
train['Zip'] =train['latlng'].apply(geolocator.reverse)
train['Zip'].apply(lambda x: pd.Series(x.split(',')))
foo = lambda x: pd.Series([i for i in reversed(x.split(','))])
train['Zip']=train['Zip'].apply(lambda x: str(x))
train['Zip']=train['Zip'].apply(foo)[1]

train

目前,我收到的错误是:

AttributeError: 'Location' object has no attribute 'split'

我如何分割位置以便我可以拿起邮政编码?

3 个答案:

答案 0 :(得分:1)

如果你想要的只是邮政编码,你可以直接访问Location对象中的邮政编码属性。

`location.raw['address']['postcode`]

答案 1 :(得分:1)

在geopy版本1.21.0中并使用导入

Give me a positive number, or 'q' to quit: a
Invalid number, try again
Give me a positive number, or 'q' to quit: 0
Number must be greater than 0
Give me a positive number, or 'q' to quit: 2
2
1
Give me a positive number, or 'q' to quit: 3
3
10
5
16
8
4
2
1
Give me a positive number, or 'q' to quit: q
Quit

我无法使用from geopy.geocoders import Nominatim 。 location.raw的示例为

location.raw["address"]

我代替了 follows: {'place_id': 3330757, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'osm_type': 'node', 'osm_id': 368381231, 'boundingbox': ['39.6634459', '39.6934459', '-75.6213155', '-75.5913155'], 'lat': '39.6784459', 'lon': '-75.6063155', 'display_name': 'New Castle County Airport, South Hollow Road, Manor Park, New Castle County, Delaware, 19721, United States of America', 'class': 'aeroway', 'type': 'aerodrome', 'importance': 0.6780150946188139, 'icon': 'https://nominatim.openstreetmap.org/images/mapicons/transport_airport2.p.20.png'} 对我有用。

答案 2 :(得分:0)

addressdetails=True传递给Nominatim以获取此信息(https://geopy.readthedocs.io/en/stable/#nominatim

location = geolocator.geocode(query={'postalcode':'95119'}, addressdetails=True)
print(location)
location.raw

产生

San Jose, Santa Clara County, California, 95119, United States of America
{'place_id': 237756323,
 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
 'boundingbox': ['37.072728062914',
  '37.392728062914',
  '-121.94612695296',
  '-121.62612695296'],
 'lat': '37.23272806291426',
 'lon': '-121.78612695295647',
 'display_name': 'San Jose, Santa Clara County, California, 95119, United States of America',
 'class': 'place',
 'type': 'postcode',
 'importance': 0.33499999999999996,
 'address': {'city': 'San Jose',
  'county': 'Santa Clara County',
  'state': 'California',
  'postcode': '95119',
  'country': 'United States of America',
  'country_code': 'us'}}