0

Tying to use Pandas dataframe Apply() function for updating all rows with a function. Result is a TypeError

----> 1 df_usnews['AvgMathSAT_IQR'].apply(interquartile(df_usnews))

/anaconda/lib/python3.5/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   2235             values = lib.map_infer(values, boxer)
   2236 
-> 2237         mapped = lib.map_infer(values, f, convert=convert_dtype)
   2238         if len(mapped) and isinstance(mapped[0], Series):
   2239             from pandas.core.frame import DataFrame

pandas/src/inference.pyx in pandas.lib.map_infer (pandas/lib.c:63043)()

TypeError: 'Series' object is not callable

def interquartile(df):
        return pd.to_numeric(df.ThirdQuartileMathSAT) - pd.to_numeric(df.FirstQuartileMathSAT)


q75_upper = np.percentile(df_usnews.AvgMathSAT, q=75, interpolation='higher', axis=0)
q25_lower = np.percentile(df_usnews.AvgMathSAT, q=25, interpolation='lower', axis=0)
interquartile = q75_upper - q25_lower
df_usnews['AvgMathSAT_IQR'] = 0
df_usnews['AvgMathSAT_IQR'].apply(interquartile(df_usnews))
3
  • The output of interquartile(df) is a Series object.You are trying to apply a Series as a function. Hence the error. Commented Oct 22, 2018 at 19:51
  • Can you share same input data, including desired output, so we can show you how apply works? Commented Oct 22, 2018 at 19:51
  • Sample data : -1 -1 138 26 38 144 -1 22 116 47 -1 2 -1 156 156 81 -1 Name: AvgMathSAT Commented Oct 22, 2018 at 20:32

1 Answer 1

2

Fixing your code, since interquartile operates on the DataFrame, apply must as well. You'd need to do

df_usnews['AvgMathSAT_IQR'] = df_usnews.apply(interquartile)

Note that when passing the function to apply, it is passed without arguments (i.e., it is not called).

Thankfully, pd.to_numeric is vectorised, so you don't need to apply the function here.

df_usnews['AvgMathSAT_IQR'] = interquartile(df_usnews)

Or,

df_usnews['AvgMathSAT_IQR'] = df_usnews.pipe(interquartile)

Is going to be a lot faster.

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.