求实现基于索引计算时间戳数组两种差值的函数
Hey there! Let's get your time difference function working correctly, and make it efficient using numpy's vectorized operations (way better than loops for this kind of task).
First, let's fix the issues with your original code
Your current code has a few problems that prevent it from working as expected:
range(timestamps)is invalid becausetimestampsis a numpy array, not an integer. You'd needrange(len(timestamps)), but even then...- The loop will hit index errors: when
i=0,i-1 = -1(which grabs the last element of the array, not what you want), and whenireaches the last index,i+1goes out of bounds. - You're overwriting
dtimes_1anddtimes_2in each loop iteration, so you'll only get the last calculated values instead of a full array.
Here's the corrected implementation
This version handles your requirements perfectly, works with both 1D and 2D (column vector) inputs, and uses numpy's fast vectorized operations:
import numpy as np def delta(timestamps): """Accrual periods: calculate two types of time differences Args: timestamps: numpy array (1D or 2D column vector) of time values Returns: dtimes_1: array where each element is Ti - Ti-1 (first element = 0) dtimes_2: array where each element is Ti+1 - Ti-1 (first element = 0) """ # Convert input to 1D for easier slicing, then restore shape later if needed ts = timestamps.flatten() n = len(ts) # Initialize result arrays with 0 (matches your example's first element) dtimes_1 = np.zeros(n - 1) dtimes_2 = np.zeros(n - 1) # Fill in the actual differences using numpy slicing (no loops needed!) # For dtimes_1: Ti - Ti-1 for i from 1 to n-2 (matches your example) dtimes_1[1:] = ts[1:-1] - ts[:-2] # For dtimes_2: Ti+1 - Ti-1 for i from 1 to n-2 dtimes_2[1:] = ts[2:] - ts[:-2] # If original input was a 2D column vector, convert results back if timestamps.ndim == 2: dtimes_1 = dtimes_1.reshape(-1, 1) dtimes_2 = dtimes_2.reshape(-1, 1) return dtimes_1, dtimes_2
Test it with your example
Let's run the code with the sample input you provided:
# Create your sample timer (column vector) timer = np.array([[0], [1], [2], [3]]) # Or using your original method: timer = np.hstack(np.arange(4).reshape(4, 1)) dt1, dt2 = delta(timer) print("dtimes_1:\n", dt1) print("\ndtimes_2:\n", dt2)
Output:
dtimes_1: [[0.] [1.] [1.]] dtimes_2: [[0.] [2.] [2.]]
Perfect, this matches exactly what you expected!
Key notes
- Vectorization: Using numpy slicing instead of loops makes this function way faster, especially when your
timerarray is large (like hundreds/thousands of elements from many iterations). - Input flexibility: Works with both 1D arrays (e.g.,
np.arange(100)) and 2D column vectors (your originalhstack/reshapeoutput). - Boundary handling: The first element of each result is set to 0, which aligns with your sample output.
内容的提问来源于stack exchange,提问作者sauwil
相关产品推荐
相关产品推荐

