如何使用scipy.interpolate.interp1d对Pandas时间序列进行插值?
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

