在python中使用scipy.interpolate,我想删除某些值并对它们进行插值

Jas*_*Kim 2 python interpolation scipy

在我的代码中,我有某些值,例如

my_list = [725.998474, 0.0, 0.0, 0.0, 0.0, 789.507934, 792.585388, 801.612916, 799.38916, 809.280518, 809.186036, 811.899414, .... , 412.314528]
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我想对列表为 0.0 的点进行插值,因为它们是异常值。但它不起作用,因为插值仅适用于空值。

如何删除那些 0.0 值并进行插值?

jar*_*red 5

使用您提供的数据,我们可以使用 numpy 创建 x 和 y 数据的“清理”列表。您说等于 0 的值是异常值,但是使用浮点数检查相等性可能会导致问题,所以我使用了np.isclose. 删除异常值后,您可以对清理后的数据进行插值。

import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt

plt.close("all")

y = np.array([725.998474, 0.0, 0.0, 0.0, 0.0, 789.507934, 792.585388,
              801.612916, 799.38916, 809.280518, 809.186036, 811.899414, 
              412.314528])
x = np.arange(len(y))

outliers = np.isclose(y, 0)
y_clean = y[~outliers]
x_clean = x[~outliers]

spline = make_interp_spline(x_clean, y_clean)
y_interped = spline(x)

fig, ax = plt.subplots()
ax.plot(x_clean, y_clean, ".", label="cleaned", zorder=3)
ax.plot(x, y_interped, label="interpolated")
ax.legend()
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.show()
Run Code Online (Sandbox Code Playgroud)

如果,正如 @ Reinderien所建议的,您的实际条件是低于 100 的值是异常值,那么您可以将其更改为该条件(即outliers = y < 100)。