python - 如何忽略 Pandas 数据框列操作的迭代
问题描述
我的 Pandas Dataframe 有列的要求:
a) 地标 b) 纬度 c) 经度
现在,我将纬度和经度传递给 API 以获取位置的地址,因此,我的输出是:
a) 地标 b) 纬度 c) 经度 d) 地址 e) 城市
我正在使用以下代码实现它:
location = boto3.client('location', region_name='ap-northeast-1')
def get_address_and_city(row):
print("Row is: ", row)
response = location.search_place_index_for_position(IndexName='TestPlaceIndex', Position=[row[1], row[0]])
print("Response is: ", response)
try:
return (response['Results'][0]['Place']['Label'], response['Results'][0]['Place']['Municipality'])
except (IndexError, KeyError):
return (None, None)
# Get Address and city from latitude / longitude
df_api_data[['address','city']] = df_api_data[['latitude', 'longitude']].apply(get_address_and_city, axis=1, result_type ='expand')
现在,一个新的要求出现了,我们有两个选项基础优先级:
- 如果 AWS 位置服务无法在标签键中返回正确的地址(在这种情况下,它会返回 PIN 码和国家/地区,如下所示:700015,IND),那么对于那些行,我必须使用Landmark属性来填充它包含的任何内容在那一栏中。例如:这些行的 df['address'] = df['Landmark']。
- 如果 Landmark 也没有数据,如果它是空的,那么我们必须合并来自 AWS Location API 响应的其他键('SubRegion'、'Region'、'PostalCode')并构建一个地址并将地址字段估算为那。
AWS API Location Service 的示例响应是:
{
"ResponseMetadata": {
"RequestId": "bbd42662-2197-474d-9462-f948131235w2",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"date": "Wed, 25 Aug 2021 06:53:08 GMT",
"content-type": "application/json",
"content-length": "294",
"connection": "keep-alive",
"x-amzn-requestid": "bfdsf42662-2197-474d-9462-f94811c88127",
"access-control-allow-origin": "*",
"x-amz-apigw-id": "EnFRNG8XNjMFqxA=",
"access-control-expose-headers": "x-amzn-errortype,x-amzn-requestid,x-amzn-errormessage,x-amzn-trace-id,x-amz-apigw-id,date",
"x-amzn-trace-id": "Root=1-6125e8d4-671f357b217ff6c90bf78869"
},
"RetryAttempts": 0
},
"Results": [
{
"Place": {
"Country": "IND",
"Geometry": {
"Point": [
76.9158,
28.42913
]
},
"Label": "122505, IND",
"Municipality": "Gurugram Sub-District",
"PostalCode": "122505",
"Region": "Haryana",
"SubRegion": "Gurugram"
}
}
],
"Summary": {
"DataSource": "Esri",
"MaxResults": 50,
"Position": [
76.9158,
28.429129999999997
]
}
}
通过 pandas 的应用功能可以实现上述所有操作,还是我必须使用 iterrows?我知道 iterrows 是一种逐行缓慢且糟糕的操作,但我找不到任何出路。任何帮助将不胜感激。
解决方案
推荐阅读
- sas - sas:如何创建一个包含 2 个数据集中不同变量列表的变量
- angular - 在 Ionic 4/Angular 中保留路由历史记录的同时一次导航回多个页面的好方法是什么?
- excel - 如何从 EXCEL VBA 向 SAP BAPI 传递参数
- google-cloud-platform - 是否可以在没有域命名的情况下为 GCS 存储桶设置索引文件?
- java - spring 容器是否为属于同一泛型类但使用不同类型的对象创建新 bean?
- mysql - 如何在 Sequelize 中设置查询超时?
- javascript - 只刷新静态页面中的聊天记录
- authentication - 使用多个用户模型登录 nova 和 laravel
- java - 将 Hibernate xml 配置文件从 hypersql 转换为 mssql
- unity3d - Unity3d:两点之间的角度不一致