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

如何将Pandas列中括号内的文本转换为大写

Pandas列中括号内文本转大写的实现

给定包含以下内容的Pandas列:

["apple", "orange (fruit)", "banana"]

需求是将括号内的文本转换为大写,最终得到:

["apple", "orange (FRUIT)", "banana"]

实现方法

利用Pandas的str.replace方法结合正则表达式,通过向量化操作高效处理:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({'fruits': ["apple", "orange (fruit)", "banana"]})

# 替换括号内文本为大写
df['fruits'] = df['fruits'].str.replace(
    pattern=r'\((.*?)\)',
    repl=lambda match: f'({match.group(1).upper()})',
    regex=True
)

# 查看结果
print(df['fruits'].tolist())

代码说明

  • 正则表达式r'\((.*?)\)':匹配括号()及其内部的文本,其中.*?是非贪婪模式,确保只匹配单个括号内的内容
  • lambda match:捕获正则匹配到的内容,将括号内的分组文本(match.group(1))转为大写后,重新包裹回括号
  • 该方法支持处理多括号场景,比如"grape (green) (round)"会被转换为"grape (GREEN) (ROUND)"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:05:22