Python – There was a problem writing a function that filters the row data frame

There was a problem writing a function that filters the row data frame… here is a solution to the problem.

There was a problem writing a function that filters the row data frame

I’m writing a function that will act as a filter for the rows I want to use.
An example data frame is as follows:

df = pd. DataFrame()
df ['Xstart'] = [1,2.5,3,4,5]
df ['Xend'] = [6,8,9,10,12]
df ['Ystart'] = [0,1,2,3,4]
df ['Yend'] = [6,8,9,10,12]
df ['GW'] = [1,1,2,3,4]

def filter(data,Game_week):
    pass_data = data [(data['GW'] == Game_week)]

When I memorize the function filter as follows, I get an error.

df1 = filter(df,1)

The error message is

AttributeError: 'NoneType' object has no attribute 'head'

But when I use the manual filter, it works.

pass_data = df [(df['GW'] == [1])]

This is my first issue.

My second problem is that I want to filter rows with multiple GW (1,2,3) etc.

To do this, I can do the following manually:

pass_data = df [(df['GW'] == [1])|( df['GW'] == [2])| (df['GW'] == [3])]

If I want to use a list in a function input [1,2,3]
How do I write it in a function so that I can enter a range of 1 to 3?

Can anyone give a suggestion?

Thanks,

Zip

Solution

Use isin For passing a list of values instead of scalars, also filter is an existing function in python, so it’s better to change the function name:

def filter_vals(data,Game_week):
    return data[data['GW'].isin(Game_week)]

df1 = filter_vals(df,range(1,4))

Related Problems and Solutions