Using SciPy chi-square inside a function that is applied to a pandas df

Viewed 29

I have a data frame that has two numeric columns 'observed' and 'expected'. I want to write a function to calculate chi-square of these values for each row. Now, I want to use SciPy already defined chisqaure in the function as follows:

def chi_2(df, observed, expected):
    obs = np.array(df[observed])
    exp = np.array(df[expected])
    chi = scipy.stats.chisquare(obs, exp)[0]
            
    return chi

df_f2['chi_2'] = chi_2(df_f2, 'observed', 'expected')  

However, when I do so, I get the same value repeated for all rows. But if I replaced SciPy function with chi = ((obs-exp)**2)/exp, all work fine.

def chi_2(df, observed, expected):
    obs = np.array(df[observed])
    exp = np.array(df[expected])
    chi = ((obs-exp)**2)/exp
    
    return chi

But I don't understand why. Could you please explain it to me? It would be much better for me to use the already defined SciPy functions inside than writing the expressions my self. Thanks

0 Answers
Related