Search code examples
pythonpandasdataframemethod-chaining

Can I use method chaining to delete rows with a if-else condition?


Right now my df looks like this (I shorten it cause there are 20 rows).

import pandas as pd

df=pd.DataFrame({'Country': ["Uruguay", "Italy", "France"], 'Winner': ["Uruguay", "Italy", "France"]})
def f(row):
    if row['Country'] in row['Winner']:
        val = False
    else:
        val = True
    return val

df["AwayTeam"]=df.apply(f, axis=1)
df

I want to delete all the rows when AwayTeam=False. Everything's fine, until I was told that I need to build a method chain.

#Not Chained
df.drop(df[df['AwayTeam'] == False].index, inplace = True)
df = df.drop("AwayTeam", axis=1)
df
#Done for now

This is what I tried

df=(
    df.drop(
    df[df['AwayTeam'] == False].index, inplace = True)
    .drop("AwayTeam", axis=1)
)
df

Solution

  • You need to remove the inplace argument.

    df = df.drop(df[df["AwayTeam"] == False].index).drop("AwayTeam", axis=1)
    

    If it's set to True, the drop method will do the operation inplace and return None, Which means that your method chain will evaluate like this,

    df = None.drop("AwayTeam", axis=1)
    

    When it's False(Which is the default value) the operation will always return a copy of the dataframe so that you can apply other methods on it(method chaining).