pythonpivot-tablescipy.statsgini

Somersd function from scipy.stats produces type error in Python


I would like to calculate the somers d. I have the following input cross table in python as a data frame called crosstab:

0 1 2 3 4
100 80 100 4 500
50 3 2 0 38
40 0 4 0 40
2000 100 100 4 400

I try to calculate the sommers d and get the following error message:

from scipy.stats import somersd
somersd(crosstab)

TypeError: Invalid call to pythranized function `_concordant_pairs(int64[:, :] (with unsupported column-major layout))' Candidates are: - _concordant_pairs(int[:,:]) - _concordant_pairs(float[:,:])

Where is my mistake?


Solution

  • You need to use to_numpy because x in somersd should be an array-like of floats :

    out = somersd(x=crosstab.astype(float).to_numpy())
    

    ā€‹ Output :

    print(out)
    
    SomersDResult(
            statistic=-0.5710103041724046,
            pvalue=9.019579189415401e-226,
            table=array([[ 100.,   80.,  100.,    4.,  500.],
           [  50.,    3.,    2.,    0.,   38.],
           [  40.,    0.,    4.,    0.,   40.],
           [2000.,  100.,  100.,    4.,  400.]]))
    

    Input used :

    crosstab = pd.DataFrame(
        {0: [100, 50, 40, 2000],
         1: [80, 3, 0, 100],
         2: [100, 2, 4, 100],
         3: [4, 0, 0, 4],
         4: [500, 38, 40, 400]}
    )