如何使用setdiff为NumPy数组赋值及提取序列下降前峰值位置
Hey there! Let's start by recapping your existing workflow for identifying segment indices in your NumPy array, then we'll tackle how to use np.setdiff1d for array assignment.
Your Existing Peak Segment Index Workflow
First, let's lay out your code clearly for context:
You start with this array:
import numpy as np n1 = np.array([1, 1, 2, 1, 4, 5, 3, 8, 2, 9, 9])
To find the end indices of each increasing segment (where the next element is smaller than the current), you run:
wherediff = np.where(n1[1:] - n1[:-1] < 0) wherediff = wherediff[0] + 1 # Output: array([3, 6, 8])
Then you prepend 0 to mark the start of the first segment:
wherediff = np.insert(wherediff, 0, 0) # Output: array([0, 3, 6, 8])
Great job on that—this gives you the boundaries of each segment where values were increasing until a drop occurred!
Using np.setdiff1d for NumPy Array Assignment
Now, let's get to your question about using setdiff (specifically NumPy's np.setdiff1d) to assign values to an array.
np.setdiff1d returns the sorted, unique values in the first array that don't appear in the second. To use this for assignment, you'll typically pair it with boolean indexing to target the right elements or indices. Let's walk through two common use cases:
1. Assigning Values Based on Element Set Differences
Suppose you want to replace all elements in n1 that aren't in a specific set of values (say {1,2,3}) with a new value like 0. Here's how to do it:
# Define the values we want to keep unchanged keep_values = np.array([1,2,3]) # Find values in n1 that are NOT in keep_values diff_values = np.setdiff1d(n1, keep_values) # diff_values will be array([4,5,8,9]) # Create a boolean mask where elements match the difference values mask = np.isin(n1, diff_values) # Assign the new value to those positions n1[mask] = 0 # Resulting array: array([1, 1, 2, 1, 0, 0, 3, 0, 2, 0, 0])
2. Assigning Values Based on Index Set Differences
If you want to target specific indices (instead of element values), you can compute the set difference between your full index list and the indices you want to exclude:
# Reset n1 to its original state first n1 = np.array([1, 1, 2, 1, 4, 5, 3, 8, 2, 9, 9]) # Indices we want to leave unchanged exclude_indices = np.array([2,5,7]) # Get all indices in n1 that are NOT in exclude_indices all_indices = np.arange(len(n1)) assign_indices = np.setdiff1d(all_indices, exclude_indices) # Assign a new value (e.g., -1) to these indices n1[assign_indices] = -1 # Resulting array: array([-1, -1, 2, -1, -1, 5, -1, 8, -1, -1, -1])
A quick note: np.setdiff1d returns sorted results. If you need to maintain the original order of indices, you can skip creating assign_indices and use a boolean mask directly:
mask = ~np.in1d(all_indices, exclude_indices) n1[mask] = -1
This gives the same result but keeps the index order intact.
内容的提问来源于stack exchange,提问作者StatsSorceress

