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

Python中用另一DataFrame多列过滤数据(空列条件自动跳过)

使用Pandas基于多条件表(含空值)过滤DataFrame

核心思路

遍历过滤条件表(df2)的每一行,仅用该行非空列作为过滤规则,将每行过滤得到的结果合并,最终得到符合所有有效条件组合的数据集。全程保留df2的原始结构,不删除任何列。

示例数据构造

先模拟题目中的原始数据和过滤条件表:

import pandas as pd
import numpy as np

# 原始数据df1
df1 = pd.DataFrame({
    'City': ['NY', 'LA', 'Chicago', 'NY', 'Boston'],
    'District': ['Manhattan', 'Hollywood', 'Downtown', 'Brooklyn', 'Cambridge'],
    'Town': ['DC', 'LA', 'NJ', 'DC', 'NJ'],
    'Country': ['USA', 'USA', 'USA', 'USA', 'USA'],
    'Continent': ['North America', 'North America', 'North America', 'North America', 'North America']
})

# 过滤条件表df2(空列用NaN表示,保留所有列)
df2 = pd.DataFrame({
    'City': ['NY', np.nan],
    'District': [np.nan, np.nan],
    'Town': ['DC', 'NJ'],
    'Country': [np.nan, np.nan],
    'Continent': [np.nan, np.nan]
})

实现过滤逻辑

# 存储所有符合条件的结果
filtered_results = []

# 遍历df2的每一行条件
for _, row in df2.iterrows():
    # 筛选出当前行非空的条件列(键值对)
    conditions = row[row.notna()].to_dict()
    # 生成过滤用的布尔索引:所有条件同时满足
    mask = pd.Series([True] * len(df1))
    for col, val in conditions.items():
        mask &= (df1[col] == val)
    # 将符合条件的行加入结果列表
    filtered_results.append(df1[mask])

# 合并所有结果并去重(避免同一行被多个条件匹配)
final_df = pd.concat(filtered_results).drop_duplicates().reset_index(drop=True)

结果验证

运行上述代码后,final_df会包含:

  • 符合第一行条件(City=NY且Town=DC)的行
  • 符合第二行条件(Town=NJ)的行

完全匹配题目要求,且df2的所有列始终保持原始状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:35:19