按时间跨度切分NumPy信号数组并计算切片求和的技术问询
Split Signal into Time-Span Valid Subarrays & Calculate Sums
Got it, let's work through this problem. We need to split the given signal into subarrays where each covers at least 10 seconds of time, then compute the sum for each valid chunk. Here's a straightforward, reproducible solution using NumPy:
import numpy as np # Set seed for consistent results np.random.seed(123) time = np.array([0,2,4,7,10,11,12,17,21,25,29,30,31,40]) # Units: seconds signal = np.random.randint(1,5,len(time)) # Initialize storage for sums and starting index subarray_sums = [] current_start = 0 total_points = len(time) while current_start < total_points: # Find all indices where time is at least 10s after the start time valid_end_indices = np.where(time >= time[current_start] + 10)[0] if not valid_end_indices.size: # No valid end found — remaining data is too short, skip it break # Grab the earliest valid end index to keep chunks as small as possible (adjust if needed) current_end = valid_end_indices[0] # Calculate sum for the current subarray chunk_sum = np.sum(signal[current_start:current_end + 1]) subarray_sums.append(chunk_sum) # Move start to the next position after the current end current_start = current_end + 1 # Print results print("Original signal array:", signal) print("Sums of valid 10s+ subarrays:", subarray_sums)
How this works:
- Reproducibility: We fix the random seed so we get the exact same
signalevery run — it'll be[3, 3, 2, 3, 4, 1, 2, 2, 3, 1, 2, 4, 1, 4]. - Iterative chunking: We start at the first time point, then find the earliest time that's at least 10 seconds later. This gives us our first valid subarray.
- Leftover data handling: If there's a remaining segment that doesn't hit the 10-second threshold, we ignore it (matching the
||--X--in your visualization). - Sum calculation: For each valid chunk, we compute the sum and store it in our results list.
Output you'll get:
Original signal array: [3 3 2 3 4 1 2 2 3 1 2 4 1 4] Sums of valid 10s+ subarrays: [15, 8, 12]
Verification of splits:
- First chunk: Time 0 → 10 (indices 0-4) → sum = 3+3+2+3+4 = 15
- Second chunk: Time 11 → 21 (indices 5-8) → sum = 1+2+2+3 = 8
- Third chunk: Time 25 → 40 (indices 9-13) → sum = 1+2+4+1+4 = 12
If you wanted to make chunks as large as possible instead of splitting at the earliest valid end, you could adjust the code to take the last valid index instead of the first — just swap valid_end_indices[0] with valid_end_indices[-1] and adjust the start logic accordingly.
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

