python - 在 Python 中插入缺失数据并记住 x 值

标签 python pandas interpolation missing-data

我需要澄清使用什么工具以及如何在 Python 中插入缺失值。引用下面的代码:

import matplotlib.pyplot as plt
from scipy import interpolate

# Create data with missing y values
x = [i for i in range(0, 10)]
y = [i**2 + i**3 for i in range(0, 10)]
y[4] = np.nan
y[7] = np.nan

# Interpolation attempt 1: Use scipy's interpolate.interp1d
f = interpolate.interp1d(x, y)
ynew = f(x)

# Interpolate attempt 2: Use pandas.Series.interpolate
yp = pd.Series(y)
yp = yp.interpolate(limit_direction='both', kind='cubic')

plt.plot(x, y, 'o', x, ynew, '-', x, yp, 'x')

plt.show()

上面的代码产生下图

Graph Plot

请注意 interp1d 行(如文档所述)如何不处理 NaN 值。

我的问题是:如何像 scipy 的 interpolation.interp1d 函数那样使用 x 值来处理 NaN 值?

谢谢

最佳答案

我会删除与 NaN 值相关的值,并为剩余的值对开发一个模型,然后对所有 x 进行预测。就像这样:

# Create data with missing y values
x = [i for i in range(0, 10)]
y = [i**2 + i**3 for i in range(0, 10)]
y[4] = np.nan
y[7] = np.nan

# convert to numpy arrays
x = np.array(x)
y = np.array(y)

# drop NaNs
idx_finite = np.isfinite(y)
f_finite = interpolate.interp1d(x[idx_finite], y[idx_finite])
ynew_finite = f_finite(x)

# Interpolation attempt 1: Use scipy's interpolate.interp1d
f = interpolate.interp1d(x, y)
ynew = f(x)

# Interpolate attempt 2: Use pandas.Series.interpolate
yp = pd.Series(y)
yp = yp.interpolate(limit_direction='both', kind='cubic')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o',label="true")
ax.plot(x, ynew, '-',label="interp1d")
ax.plot(x, ynew_finite, '--',label="interp1d finite")
ax.plot(x, yp, 'x',label="pandas")
plt.legend()
plt.show()

enter image description here

希望这有帮助!

关于python - 在 Python 中插入缺失数据并记住 x 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49360576/

相关文章:

python - 让 HTML 在 django 管理显示中换行

python - 将一列值的总和除以数据框中所有行的计数

python - Pandas 添加新列性能问题

python - 如何使不同长度的不同数据帧变得长度相等(下采样和上采样)

python - Python 中的环绕(圆形)2D 插值

python - 从 cv2 解读索贝尔

python - bash 脚本包含 perl 代码 - 并在 Python 上运行

Python 字典和列表

python替换数据框 Pandas 中所有列的多个值

c++ - 我怎样才能最好地提高双三次插值算法的执行时间?