如何访问库中下划线开头的函数?scipy.stats._kendall_dis调用问题
scipy.stats._kendall_dis Hey there, I’ve dealt with this exact frustration before—underscore-prefixed functions like _kendall_dis in SciPy are marked as internal implementation details, so direct imports are intentionally blocked to prevent breaking changes when SciPy updates. Let’s go through your options:
1. Use the Public API Instead (Recommended)
_kendall_dis is a helper function used under the hood by scipy.stats.kendalltau, which is the official, stable way to calculate Kendall’s tau correlation. If your goal is to compute Kendall-related statistics, stick with the public function:
from scipy.stats import kendalltau x = [1, 2, 3, 4, 5] y = [2, 1, 4, 3, 5] tau, p_value = kendalltau(x, y) print(f"Kendall's tau: {tau}, p-value: {p_value}")
This avoids any dependency on internal code that might change without warning.
2. Reimplement the Logic (If You Really Need _kendall_dis Behavior)
If you specifically need the Kendall distance calculation that _kendall_dis handles, you can reimplement its core logic in Python. The function computes the number of discordant pairs between two ranked sequences. Here’s a straightforward Python implementation:
def kendall_dis(x, y): # Ensure both sequences are of the same length if len(x) != len(y): raise ValueError("x and y must have the same length") # Create pairs of ranks pairs = list(zip(x, y)) n = len(pairs) discordant = 0 # Count discordant pairs for i in range(n): xi, yi = pairs[i] for j in range(i + 1, n): xj, yj = pairs[j] if (xi - xj) * (yi - yj) < 0: discordant += 1 return discordant
This replicates the core functionality of _kendall_dis without relying on internal SciPy code.
3. Bypass the Import Block (Not Recommended)
If you absolutely must use the original Cython implementation (e.g., for performance), you can access it via module introspection—but this is risky, as internal functions can be renamed or removed in future SciPy versions:
import scipy.stats # Access the internal function directly from the module's namespace _kendall_dis = scipy.stats._kendall_dis # Use it as needed (check SciPy's source for the correct parameters!) distance = _kendall_dis([1,2,3], [3,2,1])
Only do this if you’re locked into a specific SciPy version and can accept the maintenance burden of updating your code if the internal API changes.
内容的提问来源于stack exchange,提问作者Alexander Ivanov

