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

如何获取多个dataframe共有索引对应行并标记其所属dataframe

实现步骤

  1. 为每个原始数据框添加来源标记列,记录行所属的原始数据框序号
  2. 合并所有数据框
  3. 筛选出在至少2个数据框中出现过的索引对应的行,重命名索引列即可得到结果

完整代码

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({'col1': [123,121,111], 'col2': [456,454,444], 'col3': [786,787,777]}, index=['a','b','c'])
df2 = pd.DataFrame({'col1': [13,11,11], 'col2': [46,44,44], 'col3': [86,87,77]}, index=['d','e','c'])
df3 = pd.DataFrame({'col1': [1231,1214,1115,12], 'col2': [4567,4546,4445,12], 'col3': [1786,1787,1777,10]}, index=['d','g','h','c'])

# 1. 将所有待处理的df放入列表,7个数据框直接全部添加到该列表即可
df_list = [df1, df2, df3]

processed_dfs = []
for num, df in enumerate(df_list, start=1):
    tmp = df.copy()
    # 新增列标记当前行所属的原始数据框序号
    tmp['dfcol'] = num
    processed_dfs.append(tmp)

# 2. 合并所有数据框
merged_df = pd.concat(processed_dfs, axis=0)

# 3. 筛选出出现次数≥2的索引(即至少在两个数据框中存在的索引)
keep_index = merged_df.index.value_counts()[lambda x: x >= 2].index

# 4. 过滤得到目标结果,重命名索引列为newcol
newdf = merged_df.loc[keep_index].rename_axis('newcol').reset_index()

输出验证

执行上述代码后newdf的输出与你期望的结果完全一致:

newcol  col1  col2  col3  dfcol
0      c   111   444   777      1
1      c    11    44    77      2
2      c    12    12    10      3
3      d    13    46    86      2
4      d  1231  4567  1786      3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:45:02