votes up 1

`spearmanr` needs at least 2 variables to compare

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

out = _chk_asarray(a, axis)
    if a.ndim > 2:
        raise ValueError("spearmanr only handles 1-D or 2-D arrays")

    if b is None:
        if a.ndim < 2:
            raise ValueError("`spearmanr` needs at least 2 "
                             "variables to compare")
    else:
        # Concatenate a and b, so that we now only have to handle the case
        # of a 2-D `a`.
        b, _ = _chk_asarray(b, axis)
        if axisout == 0:
            a = np.column_stack((a, b))
        else

Ways to fix

votes up 1 votes down

scipy.stats.spearmanr expects a 2D shaped input. Thismeas either a has to be 2 dimensional or b should be given along side a if a is 1D.

Code to reproduce the exception:

from scipy import stats
stats.spearmanr([1,2,3,4,5])

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-3b04ea67ca9c> in <module>()  1 from scipy import stats ----> 2 stats.spearmanr([1,2,3,4,5]) 
/usr/local/lib/python3.7/dist-packages/scipy/stats/stats.py in spearmanr(a, b, axis, nan_policy)  3825 if b is None:  3826 if a.ndim < 2: -> 3827 raise ValueError("`spearmanr` needs at least 2 variables to compare")  3828 else:  3829 # Concatenate a and b, so that we now only have to handle the case 
ValueError: `spearmanr` needs at least 2 variables to compare

Fixed:

from scipy import stats
stats.spearmanr([1,2,3,4,5], [5,6,7,8,7])

SpearmanrResult(correlation=0.8207826816681233, pvalue=0.08858700531354381)

Nov 25, 2021 kellemnegasi answer
kellemnegasi 18.3k

Add a possible fix

Please authorize to post fix