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

如何检测Pandas DataFrame中某列字符串是否以另一列对应字符串开头

问题原因

Series.str.startswith() 方法的首个入参仅支持单个字符串或者字符串元组,传入完整Series对象时无法按行匹配对应位置的字符串,因此会返回全NaN的结果。

正确实现方案
  • 方法1:逐行apply(写法最直观,适合小数据量)
df['match'] = df.apply(lambda x: x['B'].startswith(x['A']), axis=1)

运行后输出结果:

A          B  match
0  Sam  Samuelson   True
1  Ham       Mike  False
2  Pam     Pamela   True
  • 方法2:列表推导式(性能最优,适合十万级以上数据量)
df['match'] = [b.startswith(a) for a, b in zip(df['A'], df['B'])]
  • 方法3:向量化实现(适合避免显式循环的场景)
import numpy as np
vectorized_startswith = np.vectorize(str.startswith)
df['match'] = vectorized_startswith(df['B'], df['A'])
注意事项

如果两列存在空值/非字符串值,需要先做清洗避免报错,例如先统一转为字符串并填充空值:

df['A'] = df['A'].fillna('').astype(str)
df['B'] = df['B'].fillna('').astype(str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:24:06