如何利用np.argwhere生成的位置数组批量修改目标数组值(避免循环)
Hey there! Congrats on hitting your first month with Python—numpy’s vectorized operations can feel a bit counterintuitive at first, but you’re already asking the right questions by trying to avoid slow for loops. Let’s fix this for you!
Your goal is to modify elements in c that line up with positions where a has values greater than 3. The key here is to use numpy’s built-in indexing capabilities, which are optimized for exactly this kind of task (no loops needed!).
First, note that your c is a Python list of lists—we’ll need to convert it to a numpy array first, since native lists don’t support numpy’s advanced indexing. Here’s how to do it properly:
import numpy as np # Your original arrays a = np.arange(6).reshape(2,3) b = np.argwhere(a > 3) # Convert c to a numpy array (critical for vectorized indexing) c = np.array([[7,8,9],[10,11,12]])
Now you have two straightforward options to update c:
Option 1: Use a boolean mask (most concise)
Instead of using np.argwhere, you can directly use the boolean array generated by a > 3 to index into c. This is the most efficient and readable approach:
# Assign new values to the matching positions c[a > 3] = [99, 100] # Replace with your desired values
Option 2: Use the argwhere result (if you need to work with b explicitly)
If you already have b from np.argwhere, you can use its rows as indices. Since b is a 2D array where each row is [row, column], we slice it to get separate row and column indices:
c[b[:, 0], b[:, 1]] = [99, 100]
Either way, running this will give you the updated c:
[[ 7 8 9] [10 99 100]]
Both methods use numpy’s vectorized operations, which are executed in optimized C code under the hood. This will be drastically faster than a Python for loop, especially with large datasets—exactly what you’re looking for!
内容的提问来源于stack exchange,提问作者Vitor Pereira Vaz

