<div dir="ltr"><div><b>Intro:</b></div><div>scipy.stats.spearmanr calculates the spearman correlation between two 1D arrays, or when presented with 2D array(s), performs the same operation pairwise on the comprising 1D arrays.</div><div><div>Currently, scipy.stats.spearmanr uses scipy.stats.mstats.spearmanr under the hood which is where the issue arises.</div><div></div></div><div>When talking about matching non-NaN values between two arrays, consider these two arrays: </div><div>[1,NaN]</div><div>[2,3]</div><div>position 0 is matching (since both arrays do not have a NaN) and position 1 is not matching.</div><div><br></div><div><b><a href="https://github.com/scipy/scipy/issues/13900  ">The Issue</a>:</b></div><div>When using scipy.stats.spearmanr with <i>nan_policy='omit'</i>, it will produce the error <i>ValueError: The input must have at least 3 entries! </i> when comparing two arrays which have exactly 1 matched pair of non-NaN values, given that one of the arrays contains at least one NaN.</div><div>This becomes a problem when using spearmanr on large, sparse datasets where either only aggressive NaN filtering or manual error-catching may prevent this error.</div><div>According to the <a href="http://scipy.github.io/devdocs/dev/api-dev/nan_policy.html">nan policy doc</a> with respect to <i>nan_policy='omit'</i>:<br></div><div><blockquote style="box-sizing:border-box;margin:0px 0px 16px;padding:0px 1em;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";font-size:14px"><p style="box-sizing:border-box;margin-top:0px;margin-bottom:0px"><i>More generally, for functions that return a scalar, func(a, nan_policy='omit') should behave the same as func(a[~np.isnan(a)]).</i></p></blockquote></div><div><b>Suggested Improvement:<br></b></div><div><div>I therefore suggest that scipy.stats.mstats.spearmanr and scipy.stats.spearmanr be altered so as to return <i>SpearmanrResult(correlation=nan, pvalue=nan)</i> given two arrays that have exactly 1 matched pair of non-NaN values. I have been corresponding with mdhaber who mentioned this would be a difficult first issue for me to contribute, since it would <b>break backwards compatibility</b>. He also pointed me to <a href="https://github.com/scipy/scipy/issues/12241">another issue</a> that likely stems from the same issue, resulting in inaccurate p-values and correlation values in correlations involving arrays containing NaNs and arrays of all 0s.</div></div><div><br></div><div><b>Asking for feedback:</b></div><div>Are there reasons to prefer the error that is currently being raised?</div><div>Should scipy.stats.spearmanr instead produce an error for both the cases with and without NaNs where only a single non-NaN value is matched between two arrays, i.e. the following should also raise the error?</div><div><i>spearmanr([1], [2], nan_policy='omit')</i></div><div><br></div><div>Best,</div><div>Tobias Schraink</div></div>