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

Python中如何按位置对比pandas两个字符串列的对应字符

错误原因

你写的df['A'][0]语法是提取A列的第一行完整字符串,不是提取每行字符串的第一位,对比逻辑不符合需求,所以返回结果错误。

等效SQL substr的实现方法

Pandas针对字符串格式的列提供了.str访问器,直接用df['列名'].str[起始索引:结束索引]即可实现和SQL substr完全一致的切片效果,注意Python索引从0开始计数,你要的第1位对应索引0,第3位对应索引2。

完整实现代码

import pandas as pd
import numpy as np

# 示例数据
df = pd.DataFrame({'A' : ['a%d', 'a%', 'i%'], 
                   'B' : ['and', 'as', 'if']})

# 匹配第1位(索引0),布尔值直接转int得到0/1
df['Match_1'] = (df['A'].str[0] == df['B'].str[0]).astype(int)
# 匹配第3位(索引2),用fillna处理长度不足3位的字符串,避免返回空值
df['Match_3'] = (df['A'].str[2] == df['B'].str[2]).fillna(False).astype(int)

print(df)

输出结果

A    B  Match_1  Match_3
0  a%d  and        1        1
1   a%   as        1        0
2   i%   if        1        0

和你期望的结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:54:03