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

如何在Pandas中拆分括号后带有字符串的列?

问题原因

你原有代码的拆分逻辑是按空格分割,但待拆分的title列中[国家代码]和后续标题之间没有空格,同时你引用的列名a和实际数据集的列名title不匹配,因此无法得到预期结果。

实现代码

方法1:使用str.extract(更直观,推荐)

直接通过正则匹配提取两部分内容,适配你的需求:

import pandas as pd

# 构造测试数据集
data = {"title":["[US]Tomorrow Never Dies", "[CA]Stories We Tell"]}
df = pd.DataFrame(data)

# 正则提取:第一组匹配带[]的国家标识,第二组匹配后续标题内容
df[["Country", "Title"]] = df['title'].str.extract(r'(\[.*?\])(.*)', expand=True)
# 可选:去除Title列首尾的多余空格(如果实际数据存在的话)
df["Title"] = df["Title"].str.strip()

方法2:使用str.split零宽断言拆分

如果偏好使用split方法,可以通过零宽正向后发断言在右括号]的位置拆分:

df[["Country", "Title"]] = df['title'].str.split(r'(?<=\])', n=1, expand=True)
df["Title"] = df["Title"].str.strip()

输出结果

运行后得到的结果和你预期完全一致:

CountryTitle
[US]Tomorrow Never Dies
[CA]Stories We Tell

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:24:04