使用Places API无法替换数据集中地址值的问题求助
解决Pandas修改切片副本无效及SettingWithCopyWarning问题
问题根源
- 你创建
df_replace_add时用了data[data[["Huyện","Quận"]].isnull().sum(axis=1)==1],这行代码生成的是原DataFrame的切片副本而非视图,后续修改该副本不会同步到原数据。 - 函数内部执行
data = data[data[add_col].notna()]再次生成新副本,你最终修改的只是这个临时对象,原数据完全不受影响。 SettingWithCopyWarning是Pandas的提示:你正在修改切片副本,该操作可能无法作用到原数据。
解决方案
方案一:显式创建副本并同步修改结果
确保操作独立副本,并将修改结果同步回原数据:
import googlemaps import win32com.client as win32 API_KEY = "(MY API KEY)" map_client = googlemaps.Client(API_KEY) def replace_address(data, add_col): # 过滤非空地址行,显式创建副本 filtered_data = data[data[add_col].notna()].copy() for i in filtered_data.index: location_name = filtered_data.loc[i, add_col] response = map_client.places(query=location_name) if response['status'] == 'OK': places = response['results'] place = places[0] address = place.get('formatted_address', 'Address not available') print(f"id: {i}, Query:{location_name}, Address: {address}") filtered_data.loc[i, add_col] = address else: print(f"id: {i}, No places found or error occurred: {response['status']}") # 将修改后的数据覆盖回传入的data data.update(filtered_data) return data # 显式创建副本,避免切片副本问题 df_replace_add = data[data[["Huyện","Quận"]].isnull().sum(axis=1)==1].copy() # 调用函数并更新副本 df_replace_add = replace_address(df_replace_add, "Địa chỉ") # 同步回原DataFrame data.update(df_replace_add)
方案二:直接操作原DataFrame的目标索引(推荐)
跳过中间副本,直接定位原数据中需要修改的行索引,从根源避免副本问题:
import googlemaps import win32com.client as win32 API_KEY = "(MY API KEY)" map_client = googlemaps.Client(API_KEY) def replace_address(data, add_col): # 筛选目标行的索引:Huyện/Quận其中一个为空,且地址列非空 target_mask = (data[["Huyện","Quận"]].isnull().sum(axis=1) == 1) & data[add_col].notna() target_indices = data[target_mask].index for i in target_indices: location_name = data.loc[i, add_col] response = map_client.places(query=location_name) if response['status'] == 'OK': places = response['results'] place = places[0] address = place.get('formatted_address', 'Address not available') print(f"id: {i}, Query:{location_name}, Address: {address}") # 直接修改原DataFrame的对应行 data.loc[i, add_col] = address else: print(f"id: {i}, No places found or error occurred: {response['status']}") # 直接调用函数处理原DataFrame replace_address(data, "Địa chỉ")
关键说明
- 方案二无需处理副本同步,直接修改原数据,代码更简洁且不会触发警告。
- 若必须使用中间数据集,务必用
.copy()显式创建独立副本,避免Pandas隐式生成的切片副本导致修改无效。
内容的提问来源于stack exchange,提问作者Vũ Minh Lê
相关产品推荐
相关产品推荐

