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

删除Pandas DataFrame指定列数值最后一位实现双表合并匹配

解决方案

你只需要在执行合并操作之前,对两个表的待匹配列Mätarställning做统一的末尾位删除处理即可,具体操作如下:

步骤1:先确保待匹配列为数值类型

先把两个表的Mätarställning列统一转为整数类型,避免类型不兼容导致处理出错:

# 转换df1filt2的匹配列为整数类型
df1filt2['Mätarställning'] = pd.to_numeric(df1filt2['Mätarställning'], errors='coerce').astype('Int64')
# 转换df2filt的匹配列为整数类型
df2filt['Mätarställning'] = pd.to_numeric(df2filt['Mätarställning'], errors='coerce').astype('Int64')

步骤2:删除列数值的最后一位

有两种常用实现方式,选其一即可:

方式1:数值整除10(推荐,适合纯整数场景)

直接对整数做整除10操作,自然去掉最后一位,性能更高,完全匹配你的示例效果:

df1filt2['Mätarställning'] = df1filt2['Mätarställning'] // 10
df2filt['Mätarställning'] = df2filt['Mätarställning'] // 10

方式2:字符串切片(适合需先处理非数字字符的场景)

如果列中存在特殊字符,可以先转字符串取除最后一位外的全部内容,再转回整数:

df1filt2['Mätarställning'] = df1filt2['Mätarställning'].astype(str).str[:-1].astype('Int64')
df2filt['Mätarställning'] = df2filt['Mätarställning'].astype(str).str[:-1].astype('Int64')

步骤3:执行原有合并逻辑

把上述代码放在原有合并代码的前面即可,处理完成后再执行合并就能匹配到对应数据:

# 前面放置上述处理代码
merged_df = df1filt2.merge(df2filt, on='Mätarställning')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:18:03