'How to interpolate value in one array based on another array (combining scipy interp1d with np percentile)

If I have two numpy arrays, what is the cleanest way to interpolate the value of x that corresponds to a specific percentile in y, when array y is an NxM array?

For example,

x = np.array(
    [
        97,
        4809,
        4762,
        282,
        3879,
        17454,
        103,
        2376,
        40581,
    ]
)


y = np.array(
    [
        [
            0.14,
            0.11,
            0.29,
            0.11,
            0.09,
            0.68,
            0.09,
            0.18,
            0.5,
        ],
        [
            0.32,
            0.25,
            0.67,
            0.25,
            0.21,
            1.56,
            0.21,
            0.41,
            1.15,
        ],
    ]
)

I was hoping a combination of scipy interpolate and numpy percentile would work, but it seems scipy has an issue with the array dimensions.

f = interpolate.interp1d(y, x, axis=0) 
f(np.percentile(y, 50, axis=0))

returns ValueError: x and y arrays must be equal in length along interpolation axis.

Expected return is [0.09, 0.21].



Solution 1:[1]

You've got x and y mixed up in the code. This should do what you want:

f = interpolate.interp1d(x, y)
f(np.percentile(x, 50))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yut23