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

使用pd.concat合并Excel表后,如何实现Pandas高级排序?

Pandas合并表格的匹配处理方案

实现逻辑

从输入输出的对应关系看,核心是让col2仅保留与col1相同且原本在col2中存在过的值,其余位置留空。具体步骤:

  • 提取col2里所有非空的有效值
  • 逐行判断col1的值是否在有效值集合中,是则保留到col2,否则置空

代码实现

import pandas as pd

# 模拟合并后的数据集(实际使用时直接用你的合并表即可)
df = pd.DataFrame(
    {'col1': ['X', 'Y', 'Z', 'A', 'B'], 'col2': ['X', 'Z', 'A', None, None]},
    index=[0, 1, 2, 4, 5]
)

# 获取col2中存在的非空值集合
valid_col2 = set(df['col2'].dropna())

# 更新col2列,空值显示为空白字符串
df['col2'] = df['col1'].where(df['col1'].isin(valid_col2), '')

print(df)

运行结果

col1 col2
0    X    X
1    Y     
2    Z    Z
4    A    A
5    B     

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:05:20