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

Pandas DataFrame多条件过滤:按赛事(R)和赛马(H)筛选结果

Conditional Filtering for Race Results DataFrame

Hey there, let's work through this conditional filtering problem for your race results DataFrame. You need to retain specific H (horse) values based on each R (race) value—here are a couple of clean, efficient ways to do this with pandas:

First, let's set up your sample DataFrame for reference

import pandas as pd

# Your original race results data
data = {
    'Date': ['11182017'] * 7,
    'R': [1, 1, 1, 2, 2, 3, 3],
    'H': [1, 2, 3, 1, 2, 1, 2],
    'Fin': [2, 1, 3, 2, 1, 1, 2],
    'Win': [0, 5, 0, 0, 10, 6, 0]
}
df = pd.DataFrame(data)

Method 1: Direct Boolean Condition Combination

This approach is straightforward and easy to read for simple conditional rules:

# Define the combined filter condition
filter_condition = (
    (df['R'] == 1) & (df['H'].isin([1, 2])) |  # Keep H=1,2 when R=1
    (df['R'] == 2) & (df['H'] == 1) |          # Keep H=1 when R=2
    (df['R'] == 3) & (df['H'] == 2)            # Keep H=2 when R=3
)

# Apply the filter to get your desired results
filtered_df = df[filter_condition]

Method 2: Mapping Dictionary (Flexible for Rule Changes)

If you might need to update the allowed H values for different R races later, this method is more scalable—just modify the dictionary instead of rewriting the condition:

# Create a mapping of race (R) to allowed horses (H)
race_horse_map = {1: [1, 2], 2: [1], 3: [2]}

# Filter rows where the horse is in the allowed list for its race
filtered_df = df[df.apply(lambda row: row['H'] in race_horse_map[row['R']], axis=1)]

Result of Both Methods

Running either code will give you this filtered DataFrame:

Date  R  H  Fin  Win
0  11182017  1  1    2    0
1  11182017  1  2    1    5
3  11182017  2  1    2    0
6  11182017  3  2    2    0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:29:52