You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用scipy.interpolate.interp1d对Pandas时间序列进行插值?

Fixing ValueError with scipy.interpolate.interp1d on Pandas Datetime Indexes

Hey there! Let's sort out that ValueError: object arrays are not supported you're seeing when using scipy.interpolate.interp1d with a Pandas datetime index.

The Root Cause

Even though your DataFrame index shows as datetime64[ns], scipy.interpolate.interp1d doesn't natively handle datetime objects under the hood. When you pass the datetime index directly, scipy interprets it as an object array (since datetime instances are technically Python objects), which it can't process for interpolation.

The Solution: Convert Datetimes to Numeric Timestamps

The fix is straightforward: convert your datetime index and target interpolation points into numeric timestamp values (like nanosecond-level integers, which matches Pandas' datetime storage). Here's how to adjust your code:

from datetime import datetime
import scipy.interpolate as si
import pandas as pd

# Original dataset
d1 = datetime(2019, 1, 1)
d2 = datetime(2019, 1, 5)
d3 = datetime(2019, 1, 10)
df = pd.DataFrame([1, 4, 2], index=[d1, d2, d3], columns=['conc'])

# Convert datetime index to numeric nanosecond timestamps
x_numeric = df.index.astype('int64')
y_values = df.conc.values

# Create the interpolation function with numeric inputs
f = si.interp1d(x_numeric, y_values)

# Convert your target date to the same numeric timestamp format
target_date = datetime(2019, 1, 3)
target_numeric = pd.Timestamp(target_date).astype('int64')  # Alternatively: target_date.timestamp() * 1e9

# Run the interpolation
interpolated_value = f(target_numeric)
print(interpolated_value)  # Output: 2.5 (linear interpolation between 1 and 4 over 4 days)

Why This Works

By converting datetimes to integer timestamps, you're giving scipy.interpolate.interp1d the numeric array it expects. This avoids modifying your original dataset (no need to insert NaNs like with pandas.interpolate), which aligns perfectly with your requirement.

If you need to interpolate multiple dates at once, just convert all target dates to a numeric array and pass it to f()—it will handle batch interpolation seamlessly.

内容的提问来源于stack exchange,提问作者Mark Bakker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:37:25