[英]Why won't my program accept a Pandas data series as input?
在學校項目中為此工作。 我基本上是從Wikipedia歷史中刪除IP地址。 然后,我通過ipstack.com API運行IP地址,並且越來越長。 然后,我嘗試將lat和long推入opencage API,但這是我遇到的問題。 如果我對一個經緯度進行硬編碼並長時間輸入,則會返回一個城市。
result = geocoder.opencage([latitude, longitude], key=key, method='reverse')
print(result.city)
但是,當我嘗試遍歷經緯度較長的列表時,出現錯誤
TypeError: cannot convert the series to <class 'float'>
我想這可能與系列類型有關,但是我可能再一次完全錯了。 有任何想法嗎?
from bs4 import BeautifulSoup
import requests
from urllib.request import urlopen
import pandas as pd
import re
from opencage.geocoder import OpenCageGeocode
import geocoder
response = requests.get("https://en.wikipedia.org/w/index.php?title=Gun_laws_in_New_Hampshire&action=history")
soup = BeautifulSoup(response.text, "lxml")
bdi_text = []
for bdi_tag in soup.find_all('bdi'):
bdi_text.append(bdi_tag.text)
ip_addresses = []
for element in bdi_text:
ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', element)
if len(ip) > 0:
ip_addresses.append(ip)
api_key = '?access_key={YOUR_API_ACCESS_KEY}'
resolved_ips = []
for ips in ip_addresses:
api_call = requests.get('http://api.ipstack.com/' + ips[0] + api_key).json()
resolved_ips.append(api_call)
ip_df = pd.DataFrame.from_records(resolved_ips)
ip_df = ip_df[['city','country_code','latitude','longitude']]
key = 'my_API_key'
latitude = ip_df['latitude']
longitude = ip_df['longitude']
result = []
print(len(latitude))
for latlong in range(0,len(latitude)):
result = geocoder.opencage([latitude, longitude], key=key, method='reverse')
print(result.city)
您的實施過程很艱難。 我會做這樣的事情
def make_city(row):
result = geocoder.opencage(float(row['latitude']), #lat of target
float(row['longitude']), #long of target
key=key, #API key that I will keep to myself
method='reverse')
print(result.city)
ip_df.apply(make_city, axis = 1)
我認為它與您傳遞的類型混淆:
不確定數據的確切結構,請嘗試以下操作:
latitude = ip_df['latitude'].astype(float)
longitude = ip_df['longitude'].astype(float)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.