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
相关产品推荐
相关产品推荐

