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

Python 3.7中为DataFrame列添加字符串并创建新列问题

问题解决:拆分Pandas DataFrame列并生成URL列

原始数据

import pandas as pd

df = pd.DataFrame({
    'col1': ['ORG-1', 'ORG-2'],
    'col2': ['LOC-100052061, LOC-100032442, LOC-100042003',
             'LOC-100005615, LOC-100000912, LOC-100043831']
})

对应的DataFrame输出:

col1   col2
0  ORG-1  LOC-100052061, LOC-100032442, LOC-100042003
1  ORG-2  LOC-100005615, LOC-100000912, LOC-100043831

预期输出

col1   col2              col3                       
0  ORG-1  LOC-100052061     https://europa.eu/v1/locations/LOC-100052061
0  ORG-1  LOC-100032442     https://europa.eu/v1/locations/LOC-100032442 
0  ORG-1  LOC-100042003     https://europa.eu/v1/locations/LOC-100042003
1  ORG-2  LOC-100005615     https://europa.eu/v1/locations/LOC-100005615
1  ORG-2  LOC-100000912     https://europa.eu/v1/locations/LOC-100000912 
1  ORG-2  LOC-100043831     https://europa.eu/v1/locations/LOC-100043831

问题分析

你尝试的代码存在两个核心问题:

  • str.split(',')拆分后,col2的每个元素会带有前置空格(比如' LOC-100032442'),导致生成的URL包含无效空格;
  • 输出内容被截断是Pandas默认显示设置的限制,并非代码逻辑错误。

修正后的完整方案

1. 正确拆分并清理列内容

两种可选方法:

# 方法1:直接按「逗号+空格」作为分隔符拆分
df_exploded = df.assign(col2=df['col2'].str.split(', ')).explode('col2')

# 方法2:先拆分再统一清理空格
# df_exploded = df.assign(col2=df['col2'].str.split(',')).explode('col2')
# df_exploded['col2'] = df_exploded['col2'].str.strip()

2. 生成URL列

url_prefix = "https://europa.eu/v1/locations/"
df_exploded['col3'] = url_prefix + df_exploded['col2']

3. 取消Pandas显示截断限制

如果需要完整展示所有列内容,添加以下设置:

pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)

执行以上代码后,即可得到符合预期的输出结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:12:57