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

Pandas: 提取DataFrame单列字符串字段中包含的最大数值并生成新列

Pandas 实现方案

核心思路

  • 用正则匹配提取目标列每个字符串中的所有连续数字
  • 转换为整数后按原行分组取最大值,直接映射生成新列

完整实现代码

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'number_quotes': [
        'I have 1-50 ice-creams',
        '4 people out of 10 said hello',
        '8889 or 9500 but could be 10903'
    ]
})

# 核心计算逻辑:提取数字→转整型→按原行分组取最大值
df['max_number'] = df['number_quotes'].str.extractall(r'(\d+)').astype(int).groupby(level=0).max()

# 可选:如果存在无数字的行,可替换空值为0
# df['max_number'] = df['max_number'].fillna(0).astype(int)

print(df)

输出结果

number_quotes  max_number
0             I have 1-50 ice-creams          50
1      4 people out of 10 said hello          10
2  8889 or 9500 but could be 10903       10903

逻辑说明

  • 正则规则r'(\d+)'用于匹配所有连续的数字字符
  • str.extractall返回的结果第一层索引和原DataFrame的行索引一一对应,分组取最大值后可以直接对齐赋值给新列

内容的提问来源于stack exchange,提问作者a.WOL7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:18:03