Zephyr
Zephyr

Reputation: 1352

issue in writing function to filter rows data frame

I am writing a function that will serve as filter for rows that I wanted to use. The sample data frame is as follow:

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 recall the function filter as follow, I got an error.

df1 = filter(df,1)

The error message is

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

but when I use manual filter, it works.

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

This is my first issue.

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

For that I can manually do it as follow:

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

if I want to use in function input as list [1,2,3] how can I write it in function such that I can input a range of 1 to 3?

Could anyone please advise?

Thanks,

Zep

Upvotes: 3

Views: 63

Answers (3)

jezrael
jezrael

Reputation: 862781

Use isin for pass list of values instead scalar, also filter is existing function in python, so better is change function name:

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

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

Upvotes: 1

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use return to return data from the function for the first part. For the second, use -

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

Now apply the filter function -

df1 = filter(df,[1,2])

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Because you don't return in the function, so it will be None, not the desired dataframe, so do (note that also no need parenthesis inside the data[...]):

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

Also, isin may well be better:

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

Upvotes: 1

Related Questions