You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于列表匹配,用Pandas Lambda条件处理列字符串提取与替换

优化地理位置列的拆分与匹配处理

原始数据与初始问题

给定如下DataFrame:

import pandas as pd
data = {'id':[1,2,3,4,5,6,7], 'location':['Havana,Cuba', 'Santiago de Cuba' , 'La Habana', 'Cuba', 'Havana, Cuba', 'Santiago, Chile', 'Chile']}
df = pd.DataFrame(data)

初始使用以下代码拆分location列:

df[['location_1', 'location_2']] = df['location'].str.split('[,|.]', 1, expand=True)

但该代码存在两个问题:

  • 无法处理Santiago de Cuba这类无分隔符的字符串,拆分后无法得到location_1='Santiago de'、location_2='Cuba'的结果
  • 当location_1的值属于sample_list=['Cuba','Chile']时,无法正确将location_2替换为匹配值并清空location_1,会出现数据覆盖问题

我们需要得到如下最终结果:

id          location   location_1 location_2
0   1       Havana,Cuba       Havana       Cuba
1   2  Santiago de Cuba  Santiago de       Cuba
2   3         La Habana    La Habana           
3   4              Cuba                    Cuba
4   5      Havana, Cuba       Havana       Cuba
5   6   Santiago, Chile     Santiago      Chile
6   7             Chile                   Chile

解决方案

以下是优化后的分步处理代码:

import pandas as pd

data = {'id':[1,2,3,4,5,6,7], 'location':['Havana,Cuba', 'Santiago de Cuba' , 'La Habana', 'Cuba', 'Havana, Cuba', 'Santiago, Chile', 'Chile']}
df = pd.DataFrame(data)
sample_list = ['Cuba', 'Chile']

# 1. 处理带逗号的拆分,同时去除首尾空格
df[['location_1', 'location_2']] = df['location'].str.split(r',', 1, expand=True)
df['location_1'] = df['location_1'].str.strip()
df['location_2'] = df['location_2'].str.strip().fillna('')

# 2. 处理location_1属于目标列表的情况
match_mask = df['location_1'].isin(sample_list)
df.loc[match_mask, 'location_2'] = df.loc[match_mask, 'location_1']
df.loc[match_mask, 'location_1'] = ''

# 3. 处理无逗号但包含目标国家的字符串
for country in sample_list:
    # 筛选出包含国家但location_2为空的行
    country_mask = df['location'].str.contains(rf'\b{country}\b', regex=True) & (df['location_2'] == '')
    # 提取国家之外的部分作为location_1
    df.loc[country_mask, 'location_1'] = df.loc[country_mask, 'location'].str.replace(rf'\s+{country}$', '', regex=True).str.strip()
    df.loc[country_mask, 'location_2'] = country

# 统一空值为空白字符串
df = df.fillna('')

print(df)

代码说明

  • 第一步:仅按逗号拆分,避免不必要的分隔符干扰,同时去除拆分后字段的首尾空格,保证数据整洁
  • 第二步:通过布尔掩码识别location_1匹配目标国家的行,直接调整两列的值
  • 第三步:针对无逗号但包含目标国家的字符串,用正则匹配提取国家之外的部分,完成拆分
  • 最后统一将空值替换为空白字符串,与预期格式一致

内容的提问来源于stack exchange,提问作者Larry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:33:29