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

如何替换pandas DataFrame列单元格值 提取字符串部分并将纯数字替换为'number'

问题分析

原代码使用r'\D'匹配所有非数字字符替换为空,和提取非数字部分的需求完全相反,同时缺失全数字替换为number、去除末尾点号的处理逻辑。

实现代码
import pandas as pd

l2=['a. 12','b. 75','23', 'c/a 34', '85', 'a 32', 'b 345']
df = pd.DataFrame({'col1': l2})

# 第一步:全数字字符串替换为'number'
df['col1'] = df['col1'].str.replace(r'^\d+$', 'number', regex=True)
# 第二步:移除空格、数字开头的后半段内容,再去除末尾的点号
df['col1'] = df['col1'].str.replace(r'[\s\d].*$', '', regex=True).str.rstrip('.')

print(df)
运行结果
col1
0       a
1       b
2  number
3     c/a
4  number
5       a
6       b

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:48:01