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

Python Pandas手动选择ID查询关联标识并按value降序输出的实现问题

问题原因

你原有代码仅完成了「筛选包含目标ID的行」的逻辑,但没有对每行判断目标ID属于ColumnA还是TempB,因此无法输出要求的ID、Link两列结构,且用正则匹配的方式容易出现边界匹配错误,直接等值判断更准确。

完整实现代码

import pandas as pd

# 先确保ID列都是字符串类型避免匹配问题
df['ColumnA'] = df['ColumnA'].astype(str)
df['TempB'] = df['TempB'].astype(str)

# 获取用户输入并转成集合
select_id = input('Enter IDs to look for (separated by space): ')
target_ids = set(select_id.split())

# 第一步:筛选包含任意目标ID的行
filtered = df[df['ColumnA'].isin(target_ids) | df['TempB'].isin(target_ids)].copy()

# 第二步:生成ID和Link列
def get_id_link(row):
    if row['ColumnA'] in target_ids:
        return pd.Series([row['ColumnA'], row['TempB']])
    else:
        return pd.Series([row['TempB'], row['ColumnA']])

filtered[['ID', 'Link']] = filtered.apply(get_id_link, axis=1)

# 第三步:按value降序排序,输出指定列
result = filtered[['ID', 'Link', 'value']].sort_values(by='value', ascending=False).reset_index(drop=True)

print(result)

效果验证

输入1421222时输出和你预期完全一致,输入1421222 4312125时也符合你给出的示例结果。如果出现单条记录中ColumnA和TempB都是你选中的目标ID的场景,可自行调整get_id_link函数的逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:03