数据处理-scipy插值

numpy: 线性插值、 对数插值

scipy: 样条插值 interp1d 等

https://docs.scipy.org/doc/scipy/reference/interpolate.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# %%
import numpy as np
from numpy import log, exp, interp
import matplotlib.pyplot as plt

from scipy.interpolate import interp1d as sciInter
from scipy.interpolate import Akima1DInterpolator as sciAkima
from scipy.interpolate import PchipInterpolator as sciPchip
from scipy.interpolate import CubicSpline as sciCubic

import pandas as pd
from rich.pretty import pprint

pd.set_option("display.width", 1000)
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)

# %%
df = pd.read_csv("datas.csv")
pprint(df)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# %%
# === 对比插值方法 取值范围 = [0.1, 10]
df_it = pd.DataFrame(np.logspace(-1, 1, num=1000), columns=["x"])
pprint(df_it)

X, Y = df["xxx"], df["val"]

df_it["linear"] = df_it["x"].apply(lambda x: interp(x, X, Y))
df_it["np_log"] = df_it["x"].apply(lambda x: exp(interp(log(x), log(X), log(Y))))

df_it["Inter1"] = df_it["x"].apply(lambda x: sciInter(X, Y, kind="slinear")(x))
df_it["Inter2"] = df_it["x"].apply(lambda x: sciInter(X, Y, kind="quadratic")(x))
df_it["Inter3"] = df_it["x"].apply(lambda x: sciInter(X, Y, kind="cubic")(x))

df_it["Akima1"] = df_it["x"].apply(lambda x: sciAkima(X, Y, method="akima")(x))
df_it["PchipI"] = df_it["x"].apply(lambda x: sciPchip(X, Y)(x))
df_it["CubicS"] = df_it["x"].apply(lambda x: sciCubic(X, Y)(x))
pprint(df_it)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# %%
# === 3. plot

plt.figure(figsize=(16, 9))
plt.scatter(X, Y, color="r", marker="*", label="data")

for col in df_it.columns[1:]:
plt.plot(df_it["x"], df_it[col], linestyle="-.", lw=1, label=f"{col}")

plt.xscale("log")
plt.yscale("log")
# plt.xlim(0.1, 10)
# plt.ylim(0.0, 10)
plt.legend()
plt.grid(":")

plt.show()