无法使用 Places API 替换数据集的地址值

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

我在将地址列的原始值替换为从 Places API 响应中获得的地址时遇到问题。尽管代码及其响应一帆风顺,但

data.loc[i,add_col]=address
一定出了问题,因为应用此函数后数据集保持不变

import googlemaps
import win32com.client as win32

API_KEY = "(MY API KEY)"
map_client = googlemaps.Client(API_KEY)

def replace_address(data,add_col):
    if data[add_col].notna().any():
        data = data[data[add_col].notna()]
        for i in data.index:
            location_name = data.loc[i,add_col]
            response = map_client.places(query=location_name)

            if response['status'] == 'OK':
                places = response['results']
                place=places[0]
                name = place['name']
                address = place.get('formatted_address', 'Address not available')
                print(f"id: {i}, Query:{location_name}, Name: {name}, Address: {address}")
                data.loc[i,add_col]=address
            else:
                print("No places found or error occurred:", response['status'])
    else:
        pass

df_replace_add = data[data[["Huyện","Quận"]].isnull().sum(axis=1)==1]
replace_address(df_replace_add,"Địa chỉ")
即使我使用相应的索引器将 .loc() 更改为 .iloc() ,df_replace_add 仍然保持不变。我已经为此苦苦挣扎了几个小时,但还不知道如何解决。非常感谢任何帮助 T.T

更新:我也收到了警告。这与问题有什么关系吗:

设置复制警告: 尝试在 DataFrame 的切片副本上设置值

请参阅文档中的警告:

https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy data.loc[i,add_col]=地址

python dataframe replace google-api google-places-api
1个回答
0
投票
这是有效的新代码块,是因为我没有制作副本

data = data[data[add_col].notna()]

还是其他原因?

def replace_address(data,add_col): for i in data.index: if not pd.isna(data.loc[i, add_col]): location_name = data.loc[i, add_col] elif pd.isna(data.loc[i, add_col]) and not pd.isna(data.loc[i, "Huyện"]): location_name = data.loc[i, "Huyện"] else: continue response = map_client.places(query=location_name) if response['status'] == 'OK': places = response['results'] place=places[0] name = place['name'] address = place.get('formatted_address', 'Address not available') print(f"id: {i}, Query:{location_name}, Name: {name}, Address: {address}") data.loc[data[add_col]==location_name,add_col]=address else: print("No places found or error occurred:", response['status']) df_replace_add = data[data[["Huyện","Quận"]].isnull().sum(axis=1)==1] replace_address(df_replace_add,"Địa chỉ")
    
© www.soinside.com 2019 - 2024. All rights reserved.