1

I have a function that is based on the "code" needed to do the same thing to different dataframes. So now that function repeats itself just with the change of the dataframe's name.

def function(t, d, code):
    if code == "champion":
        temp = champion_league.loc[(champion_league['match_date'] == d) & 
                                    (champion_league['kot'] < t)]
        if temp.empty:
            return 0
        else:
            return 1

    elif code == "europe":
        temp = earopean_leagues.loc[(earopean_leagues['match_date'] == d) & 
                                    (earopean_leagues['kot'] < t)]
        if temp.empty:
            return 0
        else:
            return 1

I tried to change the df names into the given code (where the given code is the same name as one of the dataframes). But, I get an error that string doesn't have a 'loc' attribute.

def while_champion_european_leagues(t, d, code):
    temp = code.loc[(code['match_date'] == d) & (code['kot'] < t)]
    if temp.empty:
            return 0
        else:
            return 1

How can I change my function so that It won't repeat itself and will access the right df based on the given "code"?

Tali_kr
  • 13
  • 2

1 Answers1

0

You can use a mapping dict:

codes = {
    'champion': champion_league,
    'europe': european_leagues
}

def function(t, d, code):
    df = codes.get(code)  # df is champion_league or european_leagues
    temp = df.loc[(df['match_date'] == d) & (df['kot'] < t)]
    if temp.empty:
        return 0
    else:
        return 1
Corralien
  • 109,409
  • 8
  • 28
  • 52