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

如何用Python/Pandas提取下划线分隔字符串的各部分首字符?

快速实现字符串缩写的方法

一、Python原生实现(单字符串处理)

直接通过字符串分割与生成器表达式快速拼接首字母:

input_str = "Stack_over_flow"
output_str = ''.join(word[0] for word in input_str.split('_'))
print(output_str)  # 输出: Sof

逻辑清晰:split('_')将原字符串按下划线拆分为['Stack', 'over', 'flow'],遍历每个单词取首字符后用join完成拼接。

二、Pandas批量实现(列数据处理)

如果是处理DataFrame中的字符串列,推荐两种高效方式:

方法1:lambda结合split

import pandas as pd

# 构造示例数据
df = pd.DataFrame({'original': ['Stack_over_flow', 'Hello_Python_World', 'Test_case']})
# 生成缩写列
df['abbrev'] = df['original'].str.split('_').apply(lambda x: ''.join(w[0] for w in x))
print(df)

输出结果:

original abbrev
0    Stack_over_flow    Sof
1  Hello_Python_World    HPW
2          Test_case     Tc

方法2:正则提取+分组聚合

适合复杂字符串场景,通过正则匹配每个单词的首字母再拼接:

df['abbrev'] = df['original'].str.extractall(r'(\b\w)')[0].groupby(level=0).agg(''.join)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:04:55