PowerBI - Python 从邮政编码中提取城市、国家/地区

问题描述 投票:0回答:1

我在 PowerBI 仪表板中有一个名为“邮政编码”的列 我可以使用 PowerBI 中的 python 库编写脚本并提取城市、州和国家/地区名称吗?

这是我迄今为止尝试过的, 我正在使用 ODBC 连接到数据库。 我有一个返回 49,445 行的示例查询

SELECT
ID,
POSTAL_CODE
FROM EMPLOYEE_DATA;

这是我的 python 脚本,它是我的 PowerBI 报告的一部分

# 'dataset' holds the input data for this script

# Import the required library
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

# Function to extract city, state, and country from postal code
def extract_location(POSTAL_CODE):
    geolocator = Nominatim(user_agent="geoapi")
    try:
        location = geolocator.geocode(POSTAL_CODE, timeout=10)  # Adjust the timeout value as needed
        if location:
            return location.address.split(", ")[-3:]
        else:
            return ["", "", ""]  # Return empty strings if location not found
    except GeocoderTimedOut:
        return ["", "", ""]  # Retry logic: return empty strings if geocoding times out


output = dataset.apply(lambda row: extract_location(row['POSTAL_CODE']), axis=1, result_type='expand')

# Rename the output columns
output.columns = ['City', 'State', 'Country']
python powerbi-desktop postal-code
1个回答
5
投票

这里有用的两个库:

© www.soinside.com 2019 - 2024. All rights reserved.