Есть ли способ вызывать API один раз, а не два раза для каждого сгенерированного вывода? - PullRequest
3 голосов
/ 16 октября 2019

Я пытаюсь написать код более эффективно на Python. В настоящее время приложение ниже извлекает мой желаемый вывод. Однако, он делает 2 вызова на адрес

Представляет:

import pandas as pd
from geocodio import GeocodioClient

API_KEY = 'insert_your_key_here'

client = GeocodioClient(API_KEY)

customers = pd.read_csv("example.csv", header=None)
customers['address_string'] = customers[0].map(str) + ' ' + customers[1].map(str) + customers[2].map(str)

geocoded_acuracy = []
geocoded_acuracy_type = []

for address in customers['address_string'].values:
    geocoded_address = client.geocode(address)
    accuracy = geocoded_address.best_match.get("accuracy")
    accuracy_type = geocoded_address.best_match.get("accuracy_type")

    geocoded_acuracy.append(accuracy)
    geocoded_acuracy_type.append(accuracy_type)

customers['accuracy'] = geocoded_acuracy
customers['accuracy_type'] = geocoded_acuracy_type

results = customers[['address_string', 'accuracy', 'accuracy_type']]

results.to_csv('results.csv')

Хотя код запустился, и я получил желаемый вывод. Код совершает 2 вызова API на адрес. Так как существует ограничение в 2500 дней, оно быстро расходуется. Есть ли способ сделать запрос на точность и тип точности в пределах одного вызова, потому что согласно документации они просто отображаются в выходном словаре самой исходной функции прямого геокодирования. Моя цель - сделать только 1 звонок на адрес.

Представление набора данных (где строка адреса - мой единственный ввод в приведенном выше коде):

    customers['address_string']
Out[5]: 
0         21236 Birchwood Loop, 99567, AK
1               1731 Bragaw St, 99508, AK
2            300 E Fireweed Ln, 99503, AK
3               4360 Snider Dr, 99654, AK
4     1921 W Dimond Blvd # 108, 99515, AK
5                2702 Peger Rd, 99709, AK
6              1651 College Rd, 99709, AK
7              898 Ballaine Rd, 99709, AK
8        23819 Immelman Circle, 99567, AK
9             9750 W Parks Hwy, 99652, AK
10           7205 Shorewood Dr, 99645, AK
Name: address_string, dtype: object

1 Ответ

2 голосов
/ 16 октября 2019

API возвращает JSON в следующем формате:

from geocodio import GeocodioClient

client = GeocodioClient(YOUR_API_KEY)

location = client.geocode("1109 N Highland St, Arlington VA")

Возвращает:

{
  "input": {
    "address_components": {
      "number": "1109",
      "predirectional": "N",
      "street": "Highland",
      "suffix": "St",
      "formatted_street": "N Highland St",
      "city": "Arlington",
      "state": "VA",
      "zip": "22201",
      "country": "US"
    },
    "formatted_address": "1109 N Highland St, Arlington, VA 22201"
  },
  "results": [
    {
      "address_components": {
        "number": "1109",
        "predirectional": "N",
        "street": "Highland",
        "suffix": "St",
        "formatted_street": "N Highland St",
        "city": "Arlington",
        "county": "Arlington County",
        "state": "VA",
        "zip": "22201",
        "country": "US"
      },
      "formatted_address": "1109 N Highland St, Arlington, VA 22201",
      "location": {
        "lat": 38.886665,
        "lng": -77.094733
      },
      "accuracy": 1,
      "accuracy_type": "rooftop",
      "source": "Virginia GIS Clearinghouse"
    }
  ]
}

Вам нужно только выполнить запрос один раз, а затем получить всю информацию из JSON.

Для получения вашей информации

location['results'][0]['accuracy']
location['results'][0]['accuracy_type']

С вашим кодом:

  • возможно что-то вроде следующего должно работать
  • Я только обновил for-loop
for address in customers['address_string'].values:
    geocoded_address = client.geocode(address)
    accuracy = geocoded_address['results'][0]['accuracy']
    accuracy_type = geocoded_address['results'][0]['accuracy_type']

    geocoded_acuracy.append(accuracy)
    geocoded_acuracy_type.append(accuracy_type)

customers['accuracy'] = geocoded_acuracy
customers['accuracy_type'] = geocoded_acuracy_type

Новый код для пакетной обработки:

  • С учетом ваших адресов в списке:
  • Использование панд
from geocodio import GeocodioClient
import pandas as pd
from pandas.io.json import json_normalize

addresses = ['21236 Birchwood Loop, 99567, AK',
             '1731 Bragaw St, 99508, AK',
             '300 E Fireweed Ln, 99503, AK',
             '4360 Snider Dr, 99654, AK',
             '1921 W Dimond Blvd # 108, 99515, AK',
             '2702 Peger Rd, 99709, AK',
             '1651 College Rd, 99709, AK',
             '898 Ballaine Rd, 99709, AK',
             '23819 Immelman Circle, 99567, AK',
             '9750 W Parks Hwy, 99652, AK',
             '7205 Shorewood Dr, 99645, AK']

client = GeocodioClient('api key')
locations = client.geocode(addresses)
df = json_normalize(locations, 'results')

                          formatted_address  accuracy        accuracy_type                                         source address_components.number address_components.street address_components.suffix address_components.formatted_street address_components.city     address_components.county address_components.state address_components.zip address_components.country  location.lat  location.lng address_components.predirectional
 21236 Birchwood Loop Rd, Chugiak, AK 99567      1.00              rooftop                      Municipality of Anchorage                     21236            Birchwood Loop                        Rd                   Birchwood Loop Rd                 Chugiak        Anchorage Municipality                       AK                  99567                         US     61.408788   -149.486656                               NaN
        1731 Bragaw St, Anchorage, AK 99508      1.00              rooftop                      Municipality of Anchorage                      1731                    Bragaw                        St                           Bragaw St               Anchorage        Anchorage Municipality                       AK                  99508                         US     61.204899   -149.808038                               NaN
     300 E Fireweed Ln, Anchorage, AK 99503      1.00              rooftop                      Municipality of Anchorage                       300                  Fireweed                        Ln                       E Fireweed Ln               Anchorage        Anchorage Municipality                       AK                  99503                         US     61.197860   -149.878311                                 E
     300 W Fireweed Ln, Anchorage, AK 99503      0.80              rooftop                      Municipality of Anchorage                       300                  Fireweed                        Ln                       W Fireweed Ln               Anchorage        Anchorage Municipality                       AK                  99503                         US     61.198304   -149.887737                                 W
          4360 Snider Dr, Wasilla, AK 99654      1.00  range_interpolation  TIGER/Line® dataset from the US Census Bureau                      4360                    Snider                        Dr                           Snider Dr                 Wasilla     Matanuska-Susitna Borough                       AK                  99654                         US     61.584604   -149.339148                               NaN
        4360 E Snider Dr, Wasilla, AK 99654      0.90              rooftop                      Matanuska-Susitna Borough                      4360                    Snider                        Dr                         E Snider Dr                 Wasilla     Matanuska-Susitna Borough                       AK                  99654                         US     61.584226   -149.340742                                 E
          4360 Snider Dr, Wasilla, AK 99654      0.90  range_interpolation  TIGER/Line® dataset from the US Census Bureau                      4360                    Snider                        Dr                           Snider Dr                 Wasilla     Matanuska-Susitna Borough                       AK                  99654                         US     61.584903   -149.338583                               NaN
    1921 W Dimond Blvd, Anchorage, AK 99515      1.00              rooftop                      Municipality of Anchorage                      1921                    Dimond                      Blvd                       W Dimond Blvd               Anchorage        Anchorage Municipality                       AK                  99515                         US     61.139078   -149.915706                                 W
         2702 Peger Rd, Fairbanks, AK 99709      1.00              rooftop                   Fairbanks North Star Borough                      2702                     Peger                        Rd                            Peger Rd               Fairbanks  Fairbanks North Star Borough                       AK                  99709                         US     64.822680   -147.779801                               NaN
       1651 College Rd, Fairbanks, AK 99709      1.00              rooftop                   Fairbanks North Star Borough                      1651                   College                        Rd                          College Rd               Fairbanks  Fairbanks North Star Borough                       AK                  99709                         US     64.862441   -147.754823                               NaN
       898 Ballaine Rd, Fairbanks, AK 99709      1.00              rooftop                   Fairbanks North Star Borough                       898                  Ballaine                        Rd                         Ballaine Rd               Fairbanks  Fairbanks North Star Borough                       AK                  99709                         US     64.899323   -147.828632                               NaN
      23819 Immelman Cir, Chugiak, AK 99567      1.00              rooftop                      Municipality of Anchorage                     23819                  Immelman                       Cir                        Immelman Cir                 Chugiak        Anchorage Municipality                       AK                  99567                         US     61.417786   -149.438269                               NaN
                         Big Lake, AK 99652      0.33                place  TIGER/Line® dataset from the US Census Bureau                       NaN                       NaN                       NaN                                 NaN                Big Lake     Matanuska-Susitna Borough                       AK                  99652                         US     61.517340   -149.953740                               NaN
        7205 Shorewood Dr, Palmer, AK 99645      1.00  range_interpolation  TIGER/Line® dataset from the US Census Bureau                      7205                 Shorewood                        Dr                        Shorewood Dr                  Palmer     Matanuska-Susitna Borough                       AK                  99645                         US     61.625942   -149.266667                               NaN
      7205 E Shorewood Dr, Palmer, AK 99645      0.90              rooftop                      Matanuska-Susitna Borough                      7205                 Shorewood                        Dr                      E Shorewood Dr                  Palmer     Matanuska-Susitna Borough                       AK                  99645                         US     61.626537   -149.268727                                 E
        7205 Shorewood Dr, Palmer, AK 99645      0.90  range_interpolation  TIGER/Line® dataset from the US Census Bureau                      7205                 Shorewood                        Dr                        Shorewood Dr                  Palmer     Matanuska-Susitna Borough                       AK                  99645                         US     61.625909   -149.266960                               NaN
...