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

如何参考DataFrame的area列提取team列中的队名字符串?

拆分NHL队名的解决方案

不需要手动判断地区是单词还是双词,直接利用每行的area值从team列中移除对应内容,就能精准提取队名:

方法1:逐行处理(简单直观)

用apply遍历每一行,把team里对应area的部分替换为空,再清理掉多余空格:

import pandas as pd

nhl_df = pd.DataFrame({
    "team": ["Tampa Bay Lightning", "Boston Bruins", "Toronto Maple Leafs",
             "Florida Panthers", "Detroit Red Wings"],
    "area": ["Tampa Bay", "Boston", "Toronto", "Florida", "Detroit"]})

nhl_df['teamname'] = nhl_df.apply(lambda x: x['team'].replace(x['area'], '').strip(), axis=1)

方法2:向量化操作(大数据集更高效)

如果数据量较大,用向量化字符串操作比逐行处理更快,还能通过正则边界匹配避免误替换:

nhl_df['teamname'] = nhl_df['team'].str.replace(r'^' + nhl_df['area'] + r'\s*', '', regex=True)

两种方法运行后,nhl_df的teamname列都会得到预期结果:Lightning、Bruins、Maple Leafs、Panthers、Red Wings。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:42:03