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

不同大小DataFrame字符串匹配:获取首次匹配索引与列值

提取DataFrame中首次匹配项的索引与对应列值

问题场景

现有两个不同大小的DataFrame:

  • df1为短表,type列无重复值
  • df2为长表,type列存在重复值

需要为df1的每一行type值,在df2中找到首次匹配的记录,返回该记录的索引和color列值,并合并到df1中。

示例数据

import pandas as pd

df1 = pd.DataFrame({'type':['Apple3','Pear28','Banana0','Lime46']}) 
df2 = pd.DataFrame({'type':['Apple2','Apple3','Lime46','Apple3','Lime46','Pear28'],
                    'color':['red','orange','green','orange','green','yellow']})

预期结果

最终df1需新增ind(匹配到的df2索引)和color列,无匹配项填充NaN:

typeindcolor
Apple31orange
Pear285yellow
Banana0NaNNaN
Lime462green

解决方案

方法1:去重后左连接

先提取df2中每个type的首次出现记录,再与df1做左连接:

# 给df2添加索引列,方便提取匹配索引
df2['ind'] = df2.index

# 保留每个type的首次出现记录
df2_first = df2.drop_duplicates(subset='type', keep='first')

# 左连接合并,保留df1所有行
result_df = pd.merge(df1, df2_first[['type', 'ind', 'color']], on='type', how='left')

# 将索引列转为字符串格式,匹配预期的NaN展示
result_df['ind'] = result_df['ind'].astype(str).replace('nan', 'NaN')

print(result_df)

方法2:分组取首项

通过groupby按type分组,直接提取每组的第一个记录:

# 提前给df2添加索引列
df2['ind'] = df2.index
# 分组获取每个type的首次记录,重置索引
df2_first = df2.groupby('type', as_index=False).first()

# 左连接合并
result_df = pd.merge(df1, df2_first[['type', 'ind', 'color']], on='type', how='left')
result_df['ind'] = result_df['ind'].astype(str).replace('nan', 'NaN')

print(result_df)

说明

  • drop_duplicates(subset='type', keep='first'):确保只保留每个type第一次出现的行
  • 左连接(how='left'):保证df1的所有行都被保留,无匹配项的字段自动填充NaN
  • 转换索引为字符串并替换nan为NaN:完全匹配示例中的预期格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:54:51