You need to enable JavaScript to run this app. 如何使用一个DataFrame的列值过滤另一个DataFrame的指定列数据
优惠活动
大模型
产品
解决方案
定价
更多

如何使用一个DataFrame的列值过滤另一个DataFrame的指定列数据

Pandas 多阈值筛选子表实现方案

需求梳理

遍历df2的Var列每个取值,筛选df1中Grand Total列大于当前Var值的所有行,为每个Var值生成独立子DataFrame。

实现代码

独立实现版本

直接对已有的df1、df2处理,结果存入字典方便取用:

import pandas as pd

# 结果字典,key为对应CI值,value为筛选后的子DataFrame
filtered_result = {}

for _, row in df2.iterrows():
    current_ci = row['CI']
    current_var = row['Var']
    # 按条件筛选
    sub_df = df1[df1['Grand Total'] > current_var].copy()
    filtered_result[current_ci] = sub_df

# 取用示例:获取CI=60对应的筛选结果
print(filtered_result[60.0])

集成到现有类版本

可以直接把筛选逻辑加到你已写的varmethod方法中,不用额外调整原有逻辑:

def varmethod(self,CI,simulationDf):
    total = simulationDf['Grand Total'].sum() 
    df = pd.DataFrame(CI,columns=['CI'])
    for value,data in enumerate(CI): 
        CI[value]=(data/100)*(total)
    df['Var'] = CI
    # 新增筛选逻辑
    filtered_result = {}
    for _, row in df.iterrows():
        current_ci = row['CI']
        current_var = row['Var']
        sub_df = simulationDf[simulationDf['Grand Total'] > current_var].copy()
        filtered_result[current_ci] = sub_df
    print(df)
    # 原有返回基础上新增返回筛选结果字典
    return df, filtered_result

注意事项

  • 你给出的示例df1中所有行的Grand Total最大值为2.106283e+72,小于df2最小的Var值3.009765e+72,示例数据下所有筛选结果都会是空表,实际运行时如果模拟次数足够,有符合条件的行就会正常返回数据。
  • 代码中加copy()是为了避免修改筛选后的子表时影响原DataFrame,不需要可以删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 09:15:04