如何从DataFrame的Animals列提取特定词汇并生成对应新行?
问题:从DataFrame的Animals列提取特定分类词汇并新增行
原始DataFrame
| Animals | Type | Year |
|---|---|---|
| Penguin AVES | Omnivore | 2015 |
| Caiman REP | Carnivore | 2018 |
| Komodo.Rep | Carnivore | 2019 |
| Blue Jay.aves | Omnivore | 2015 |
| Peregrine aves Falcon | Carnivore | 2016 |
| Iguana+rep | Carnivore | 2020 |
| Rep Salamander | Carnivore | 2019 |
预期结果
需要提取AVES/REP及其大小写变体(如aves、Rep、rep),在原行下方新增一行数据,新行的Type和Year与原行一致,Animals为提取出的词汇,最终得到:
| Animals | Type | Year |
|---|---|---|
| Penguin AVES | Omnivore | 2015 |
| AVES | Omnivore | 2015 |
| Caiman REP | Carnivore | 2018 |
| REP | Carnivore | 2018 |
| Komodo.Rep | Carnivore | 2019 |
| Rep | Carnivore | 2019 |
| Blue Jay.aves | Omnivore | 2015 |
| aves | Omnivore | 2015 |
| Peregrine aves Falcon | Carnivore | 2016 |
| aves | Carnivore | 2016 |
| Iguana+rep | Carnivore | 2020 |
| rep | Carnivore | 2020 |
| Rep Salamander | Carnivore | 2019 |
| Rep | Carnivore | 2019 |
当前代码局限
现有代码仅能提取位于字符串末尾的目标词汇:
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"这两个目标词汇,自动跳过周围的空格、点、+等分隔符,无论目标词汇在字符串的开头、中间还是末尾。
代码逻辑解释
df['Animals'].str.extract(r'(?i)(aves|rep)'):从每行的Animals字符串中提取匹配到的目标词汇df.assign(Animals=...):将提取出的词汇替换原Animals列,生成仅包含目标词汇的新行数据pd.concat([df, ...]):将原始数据和新行数据合并sort_index(kind='stable', ignore_index=True):保持原行与对应新行的顺序(原行在前,新行在后),并重新生成连续的索引。
内容的提问来源于stack exchange,提问作者SimplyWilly
相关产品推荐
相关产品推荐

