TJB*_*TJB 2 python pyspark databricks
在下面的代码块中,我有一个数据帧geo,我想对其进行迭代以获取 中每个英国邮政编码的东距、北距、经度和纬度geo。我编写了一个函数来调用 API,另一个函数则返回四个变量。
我已经使用get_data邮政编码测试了该调用,以证明它有效(这是任何人都可以使用的公共 API):
import requests
import pandas as pd
geo = spark.table('property_address').toPandas()
def call_api(url: str) -> dict:
postcode_response =requests.get(url)
return postcode_response.json()
def get_data(postcode):
url = f"http://api.getthedata.com/postcode/{postcode}"
req = r.get(url)
results = req.json()['data']
easting = results['easting']
northing = results['northing']
latitude = results['latitude']
longitude = results ['longitude']
return easting ,northing,latitude, longitude
get_data('SW1A 1AA')
Run Code Online (Sandbox Code Playgroud)
返回:
Out[108]: (529090, 179645, '51.501009', '-0.141588')
Run Code Online (Sandbox Code Playgroud)
我想要做的是为每一行运行它geo并将其作为数据集返回。我的研究引导我apply,并且我的尝试基于本指南。
我试图传递一个调用的列property_postcode并geo迭代每一行以返回值,这是我的尝试:
def get_columns(row):
column_name = 'property_postcode'
api_param = row[column_name]
easting,northing,latitude,longitude = get_data(api_param)
row['east'] = easting
row['north'] = northing
row['lat'] = latitude
row['long'] = longitude
return row
geo= geo.apply(get_columns, axis=1)
display(geo)
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
`JSONDecodeError: Expecting value: line 1 column 1 (char 0)`
Run Code Online (Sandbox Code Playgroud)
并没有告诉我很多。寻求帮助\指点。
不要尝试在函数中设置东、北、纬度和长列的值,而是从函数返回它们。
from numpy import result_type
import requests
import pandas as pd
# geo = spark.table('property_address').toPandas()
def call_api(url: str) -> dict:
postcode_response = requests.get(url)
return postcode_response.json()
def get_data(postcode):
url = f"http://api.getthedata.com/postcode/{postcode}"
req = requests.get(url)
if req.json()["status"] == "match":
results = req.json()["data"]
easting = results.get("easting")
northing = results.get("northing")
latitude = results.get("latitude")
longitude = results.get("longitude")
else:
easting = None
northing = None
latitude = None
longitude = None
return easting, northing, latitude, longitude
def get_columns(code):
api_param = code
return get_data(api_param)
df = pd.DataFrame(
{
"property_postcode": [
"BE21 6NZ",
"SW1A 1AA",
"W1A 1AA",
"DE21",
"B31",
"ST16 2NY",
"S65 1EN",
]
}
)
df[["east", "north", "lat", "long"]] = df.apply(
lambda row: get_columns(row["property_postcode"]), axis=1, result_type="expand"
)
print(df)
Run Code Online (Sandbox Code Playgroud)
| 属性_邮政编码 | 东方 | 北 | 拉特 | 长的 |
|---|---|---|---|---|
| BE21 6NZ | 南 | 南 | 没有任何 | 没有任何 |
| SW1A 1AA | 529090 | 179645 | 51.501009 | -0.141588 |
| W1A 1AA | 528887 | 181593 | 51.518561 | -0.143799 |
| DE21 | 南 | 南 | 没有任何 | 没有任何 |
| B31 | 南 | 南 | 没有任何 | 没有任何 |
| ST16 2纽约 | 391913 | 323540 | 52.809346 | -2.121413 |
| S65 1EN | 444830 | 394082 | 53.44163 | -1.326573 |
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |