Numpy索引越界报错求助:IndexError索引10超出轴1尺寸10
Hey there! Let's break down why you're hitting that IndexError and how to fix it.
What's Going Wrong?
Your array Z has a shape of (500, 10)—that means it has 500 rows, each with 10 elements. Valid indices for the second axis (columns) only go from 0 to 9 here. But your y array is np.arange(500), which generates values from 0 all the way up to 499. When you use Z[range(500), y], you're trying to index columns with numbers like 10, 11, ..., 499—way beyond the 10-element limit of that axis. That's exactly why you get the error: index 10 is out of bounds for axis 1 with size 10.
How to Fix It
You need to make sure every value in y is a valid index for the second axis of Z (i.e., between 0 and 9). Depending on your intended behavior, here are a couple common solutions:
1. Cycle through the 10 columns (most likely what you wanted)
If you want to pick one element from each row, cycling through the 10 columns repeatedly, use modulo to wrap y into the valid index range:
import numpy as np Z = np.random.random((500,10)) y = np.arange(500) % 10 # Modulo 10 ensures values stay 0-9 print(Z.shape) # Output: (500, 10) print(y.shape) # Output: (500,) result = Z[range(500), y] print(result.shape) # Output: (500,) — one value per row!
2. Use valid indices only
If you meant to index each row with a random valid column index, generate y to only contain values between 0 and 9:
y = np.random.randint(0, 10, size=500) # Generates 500 integers in 0-9 range
Key Takeaway for NumPy Advanced Indexing
When using two arrays to index a 2D array (like Z[rows, cols]), every value in the cols array must be a valid index for the second axis of Z—meaning it has to be less than Z.shape[1] (which is 10 in your case).
内容的提问来源于stack exchange,提问作者Daniel Chepenko

