1

I am filtering a pandas dataframe based on one or more conditions, like so:

def filter_dataframe(dataframe, position=None, team_id=None, home=None, window=None, min_games=0):
        
        df = dataframe.copy()

        if position:
            df = df[df['position_id'] == position] 
        
        if clube_id:
            df = df[df['team_id'] == team_id]
        
        if home:
            if home == 'home':
                df = df[df['home_dummy'] == 1.0]
            elif home == 'away':
                df = df[df['home_dummy'] == 0.0]
        
        if window:
            df = df[df['round_id'].between(1, window)]
        
        if min_games:
            df = df[df['games_num'] >= min_games]

        return df

But I don't think this is elegant.

Is there a simpler way of achieving the same result?

I though of creating rules for conditions like in this SO answer and then use the method any(rules) in order to apply the filtering, if any, but I don't know how to approach this. Any ideas?

3
  • Might be better suited for codereview? Commented Mar 31, 2021 at 4:09
  • Can you try passing the column name and parameter value to filter instead of all parameters? Commented Mar 31, 2021 at 4:32
  • yes, this could be done Commented Mar 31, 2021 at 4:33

1 Answer 1

1

You could try something like this:

def filter_dataframe(dataframe, position=None, clube_id=None, team_id=None, home=None, window=None, min_games=0):
    df = dataframe.copy()
    masks = {
        "mask1": [position is not None, df[df["position_id"] == position]],
        "mask2": [clube_id is not None, df[df["team_id"] == team_id]],
        "mask3": [home == "home", df[df["home_dummy"] == 1.0]],
        "mask4": [home == "away", df[df["home_dummy"] == 0.0]],
        "mask5": [window is not None, df[df["round_id"].between(1, window)]],
        "mask6": [min_games is not None, df[df["games_num"] >= min_games]],
    }
    for value in masks.values():
        if value[0]:
            df = value[1]
    return df
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.