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

如何从DataFrame的Animals列提取特定词汇并生成对应新行?

问题:从DataFrame的Animals列提取特定分类词汇并新增行

原始DataFrame

AnimalsTypeYear
Penguin AVESOmnivore2015
Caiman REPCarnivore2018
Komodo.RepCarnivore2019
Blue Jay.avesOmnivore2015
Peregrine aves FalconCarnivore2016
Iguana+repCarnivore2020
Rep SalamanderCarnivore2019

预期结果

需要提取AVES/REP及其大小写变体(如aves、Rep、rep),在原行下方新增一行数据,新行的Type和Year与原行一致,Animals为提取出的词汇,最终得到:

AnimalsTypeYear
Penguin AVESOmnivore2015
AVESOmnivore2015
Caiman REPCarnivore2018
REPCarnivore2018
Komodo.RepCarnivore2019
RepCarnivore2019
Blue Jay.avesOmnivore2015
avesOmnivore2015
Peregrine aves FalconCarnivore2016
avesCarnivore2016
Iguana+repCarnivore2020
repCarnivore2020
Rep SalamanderCarnivore2019
RepCarnivore2019

当前代码局限

现有代码仅能提取位于字符串末尾的目标词汇:

out = (pd.concat([df, df.assign(Animals=df['Animals'].str.extract(r'(\w+)$'))])          
       .sort_index(kind='stable', ignore_index=True)       
)

解决方案

核心是使用忽略大小写的正则表达式匹配目标词汇,不管其在字符串中的位置或周围的分隔符。

修改后的代码

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Animals': ['Penguin AVES', 'Caiman REP', 'Komodo.Rep', 'Blue Jay.aves', 
                'Peregrine aves Falcon', 'Iguana+rep', 'Rep Salamander'],
    'Type': ['Omnivore', 'Carnivore', 'Carnivore', 'Omnivore', 
             'Carnivore', 'Carnivore', 'Carnivore'],
    'Year': [2015, 2018, 2019, 2015, 2016, 2020, 2019]
})

# 提取目标词汇并生成新DataFrame
out = (pd.concat([df, df.assign(Animals=df['Animals'].str.extract(r'(?i)(aves|rep)'))])
       .sort_index(kind='stable', ignore_index=True)
)

# 输出结果
print(out)

正则表达式说明

(?i)(aves|rep) 各部分含义:

  • (?i):开启忽略大小写模式,匹配时不区分AVES/aves、REP/Rep/rep等变体
  • (aves|rep):精准捕获"aves"或"rep"这两个目标词汇,自动跳过周围的空格、点、+等分隔符,无论目标词汇在字符串的开头、中间还是末尾。

代码逻辑解释

  1. df['Animals'].str.extract(r'(?i)(aves|rep)'):从每行的Animals字符串中提取匹配到的目标词汇
  2. df.assign(Animals=...):将提取出的词汇替换原Animals列,生成仅包含目标词汇的新行数据
  3. pd.concat([df, ...]):将原始数据和新行数据合并
  4. sort_index(kind='stable', ignore_index=True):保持原行与对应新行的顺序(原行在前,新行在后),并重新生成连续的索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:50:41