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

如何从DataFrame格式的数据集中移除内容中的方括号?

移除DataFrame中字符串的方括号解决方案

你的原始DataFrame数据如下:

FromTO
[wrestle]进行摔跤比赛
[write]通过写作交流或表达
[write]出版
[spell]书写
[compose]创作音乐

想要得到的目标输出是:

FromTO
wrestle进行摔跤比赛
write通过写作交流或表达
write出版
spell书写
compose创作音乐

下面给你两种实用的解决方法:

方法1:利用str.strip()移除首尾方括号

因为你的方括号都是出现在字符串的首尾位置,strip()方法可以直接指定要移除的字符集合,精准清理首尾的[和],代码简洁高效:

import pandas as pd

# 构造你的DataFrame
df = pd.DataFrame({
    'From': ['[wrestle]', '[write]', '[write]', '[spell]', '[compose]'],
    'TO': ['进行摔跤比赛', '通过写作交流或表达', '出版', '书写', '创作音乐']
})

# 移除首尾方括号
df['From'] = df['From'].str.strip('[]')

# 查看结果
print(df)

方法2:利用str.replace()全局移除方括号

如果你的数据里可能存在字符串中间带方括号的情况(或者想统一清除所有位置的[和]),可以用正则替换的方式,一次性移除所有匹配的字符:

import pandas as pd

df = pd.DataFrame({
    'From': ['[wrestle]', '[write]', '[write]', '[spell]', '[compose]'],
    'TO': ['进行摔跤比赛', '通过写作交流或表达', '出版', '书写', '创作音乐']
})

# 全局替换所有方括号
df['From'] = df['From'].str.replace(r'[\[\]]', '', regex=True)

print(df)

两种方法运行后都能得到你想要的结果,你可以根据自己的实际数据情况选择合适的方法~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:56:10