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

在Pandas DataFrame中拼接列:补全地址字段需求

地址字段拼接解决方案

问题说明

现有如下Pandas数据集:

import pandas as pd

data = {'id':  ['001', '002', '003','004'],
        'address': ["William J. Clare\n290 Valley Dr.\nCasper, WY 82604\nUSA",
                    "1180 Shelard Tower\nMinneapolis, MN 55426\nUSA",
                    "William N. Barnard\n145 S. Durbin\nCasper, WY 82601\nUSA",
                    "215 S 11th ST"],
        'locality': [None, None, None,'Laramie'],
        'region': [None, None, None, 'WY'],
        'Zipcode': [None, None, None, '87656'],
        'Country': [None, None, None, 'US']
        }

df = pd.DataFrame(data)

需要实现:

  • 前3行的address包含姓名行,要删除这一行,保留后续地址内容
  • 第4行的address缺少地区、州、邮编、国家信息,需将locality、region、Zipcode合并为Laramie, WY 87656,再加上Country内容,用\n分隔后拼接到原地址后
  • 最终得到如下格式的address列:
address
290 Valley Dr.\nCasper, WY 82604\nUSA
1180 Shelard Tower\nMinneapolis, MN 55426\nUSA
145 S. Durbin\nCasper, WY 82601\nUSA
215 S 11th ST\nLaramie, WY 87656\nUS

解决方案

直接运行以下代码即可实现需求:

import pandas as pd

data = {'id':  ['001', '002', '003','004'],
        'address': ["William J. Clare\n290 Valley Dr.\nCasper, WY 82604\nUSA",
                    "1180 Shelard Tower\nMinneapolis, MN 55426\nUSA",
                    "William N. Barnard\n145 S. Durbin\nCasper, WY 82601\nUSA",
                    "215 S 11th ST"],
        'locality': [None, None, None,'Laramie'],
        'region': [None, None, None, 'WY'],
        'Zipcode': [None, None, None, '87656'],
        'Country': [None, None, None, 'US']
        }

df = pd.DataFrame(data)

def process_address(row):
    # 把原始地址按换行符拆成多个片段
    address_lines = row['address'].split('\n')
    # 判断是否有独立列的地址信息
    if pd.isna(row['locality']):
        # 没有独立信息,删除姓名行后重新拼接地址
        return '\n'.join(address_lines[1:])
    else:
        # 有独立信息,拼接地区+州+邮编,再加上国家,拼到原地址后面
        locality_part = f"{row['locality']}, {row['region']} {row['Zipcode']}"
        return f"{row['address']}\n{locality_part}\n{row['Country']}"

# 处理每一行的address列
df['address'] = df.apply(process_address, axis=1)

# 查看处理后的结果
print(df['address'])

代码说明

  • 定义的process_address函数专门处理单条地址:
    1. 先把原始地址按\n拆成小片段,比如第一行地址会拆成['William J. Clare', '290 Valley Dr.', 'Casper, WY 82604', 'USA']
    2. 检查locality列是否为空:
      • 为空时(前3行),扔掉第一个片段(姓名),把剩下的片段用\n拼回去,得到干净的地址
      • 不为空时(第4行),把locality、region、Zipcode拼成Laramie, WY 87656格式,再加上Country内容,一起拼到原始地址后面
  • df.apply(process_address, axis=1):把这个处理逻辑应用到每一行,更新address列的值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:45:32