有效点间插值精度丢失:如何生成小数插值结果?
解决线性插值得到小数结果的问题
你的问题出在两个关键点上:Y3列的整数类型会截断插值后的小数,且插值没有基于实际的时间值计算。以下是修正方案:
1. 转换Y3列为浮点型
原始数据中Y3的有效值都是整数,pd.to_numeric会默认将其转为整数类型,导致插值后的小数被自动取整。需要明确指定转为浮点型:
df.loc[1:, "Y3"] = pd.to_numeric(df.loc[1:, "Y3"], downcast="float")
2. 基于实际时间值做插值
你之前的插值是按行的整数索引计算的,没有考虑Time列的实际时间间隔。需要先把Time列转为数值类型,再以此作为插值基准:
# 转换Time列为数值(浮点型) df.loc[1:, "Time"] = pd.to_numeric(df.loc[1:, "Time"]) # 指定x参数为Time列,基于实际时间间隔执行线性插值 df.loc[1:, "Y3"] = df.loc[1:, "Y3"].interpolate(method="linear", x=df.loc[1:, "Time"])
完整代码示例
import pandas as pd df = pd.read_csv("test.csv") # 处理Time列类型 df.loc[1:, "Time"] = pd.to_numeric(df.loc[1:, "Time"]) # 处理Y3列类型,避免插值结果被截断 df.loc[1:, "Y3"] = pd.to_numeric(df.loc[1:, "Y3"], downcast="float") # 基于时间值插值 df.loc[1:, "Y3"] = df.loc[1:, "Y3"].interpolate(method="linear", x=df.loc[1:, "Time"]) # 处理首尾的NaN(按需选择bfill/ffill) df.loc[1:, "Y3"] = df.loc[1:, "Y3"].bfill().ffill() print(df)
最终效果
执行后Y3列在1.074秒(-27)和3.123秒(-28)之间的插值会是符合时间间隔的小数,比如1.579秒对应的Y3值约为-27.24,2.083秒对应的约为-27.49,完全满足你的需求。
内容的提问来源于stack exchange,提问作者Ben Nguyen
相关产品推荐
相关产品推荐

