You need to enable JavaScript to run this app. 如何提取Python字符串中指定单词前的内容 完成DataFrame床位数统计
优惠活动
大模型
产品
解决方案
定价
更多

如何提取Python字符串中指定单词前的内容 完成DataFrame床位数统计

实现方法

方法1:使用正则提取(最简洁高效)

直接用pandas内置的str.extract匹配beds前方的数字即可:

# 匹配beds前面的1个或多个数字,转为int类型
df['beds'] = df['string'].str.extract(r'(\d+)\s+beds', expand=False).astype(int)

该方法会自动匹配所有beds前紧邻的数字,无需手动拆分字符串处理索引。

方法2:按原思路的拆分列表实现

如果要坚持用拆分字符串查索引的逻辑,可通过自定义函数+apply实现:

def extract_bed_count(s):
    words = s.strip().split()
    # 找到beds单词的索引,取前一位转int
    beds_pos = words.index('beds')
    return int(words[beds_pos - 1])

df['beds'] = df['string'].apply(extract_bed_count)

两种方法运行后得到的结果和预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 11:15:00