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

基于双DataFrame条件筛选生成新Pandas DataFrame的实现问题

实现方案

两个DataFrame表头、索引完全一致的前提下,直接调用value的where方法即可实现需求:where方法会在条件成立时保留value的对应值,条件不成立时自动填充NaN,完全匹配你要求的生成规则。
核心代码只有一行:

expected_result = value.where(rank <= filter_var)

完整可运行代码如下:

import pandas as pd

# df 1 排名数据
ranking = {'Stock A':[1, 1, 1, 1],
           'Stock B':[3, 3, 4, 4],
           'Stock C':[4, 4, 3, 2],
           'Stock D':[2, 2, 2, 3],
           }
rank = pd.DataFrame(ranking)

# df 2 数值数据
values = {'Stock A':[101, 102, 103, 104],
           'Stock B':[99, 99, 99 , 99],
           'Stock C':[99, 98, 100, 103],
           'Stock D':[100, 100, 100, 102],
           }
value = pd.DataFrame(values)

# 过滤参数
filter_var = 2

# 生成目标DataFrame
expected_result = value.where(rank <= filter_var)

如果需要和示例完全一致使用字符串格式的'nan',可以追加一行转换代码:

expected_result = expected_result.astype('object').fillna('nan')

常规数据分析场景下默认生成的pandas原生NaN更适合后续运算,无需额外转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:45:05