首页 > 解决方案 > 如何忽略 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')

现在,一个新的要求出现了,我们有两个选项基础优先级:

  1. 如果 AWS 位置服务无法在标签键中返回正确的地址(在这种情况下,它会返回 PIN 码和国家/地区,如下所示:700015,IND),那么对于那些行,我必须使用Landmark属性来填充它包含的任何内容在那一栏中。例如:这些行的 df['address'] = df['Landmark']。
  2. 如果 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 是一种逐行缓慢且糟糕的操作,但我找不到任何出路。任何帮助将不胜感激。

标签: pythonpython-3.xpandasdataframepandas-apply

解决方案


推荐阅读