Python:用for循环创建二维NumPy数组时遇IndexError问题求助
Fixing IndexError When Creating 2D NumPy Array with Nested Loops
Let's break down why you're hitting this IndexError and how to fix it step by step.
Why the Error Happens
- You initialize
result_array = np.array([])as an empty NumPy array. On the first iteration of your outer loop (h=0), you try to accessresult_array[h]—but an empty array has zero elements, so index 0 is completely out of bounds. That's exactly what the error message is flagging. - Your use of
np.appendhere is also flawed:np.appendexpects the original array and the element/array to add, but trying to index into an empty array first breaks the entire operation before the append can even run.
Fix Steps & Corrected Code
Here's how to adjust your code to build the 2D array correctly, plus some cleanup to remove redundant work:
- Use a list for iterative appends instead of an empty NumPy array
Lists are far more efficient for repeated appends, and we can convert to a NumPy array once all data is collected. - Eliminate redundant re-initializations
Variables likexpandzpdon't need to be redefined in every inner loop—this just wastes processing time. - Simplify inner loop logic
You don't need the separateinter_resultarray; just append each calculatednanmax(gz)directly tointer2d_result. - Append full 1D arrays to the result list
Skip indexing into the result during appends—just add each completedinter2d_resultto the list, then convert to a 2D NumPy array at the end.
Corrected Code
import numpy as np # Assuming mesher and talwani modules are imported correctly density = 1000 result_list = [] # Use list for efficient iterative appends visual_x = np.array([]) # Pre-define xp and zp once instead of reinitializing every loop xp = np.arange(-10000, 10000, 10.0) zp = np.zeros_like(xp) for h in range(3): # Reset polygon points for each outer loop iteration current_points = np.array([[-100, 0], [100, 0], [100, 300],[-100,300]]) inter2d_result = np.array([]) for i in range(10): poly = [mesher.Polygon(current_points, {'density': density})] gz = talwani.gz(xp, zp, poly) # Append the max value directly to our 1D result array inter2d_result = np.append(inter2d_result, np.nanmax(gz)) visual_x = np.append(visual_x, current_points[1][0] * 2) # Update polygon x-coordinates for next inner loop iteration current_points[0][0] -= 10 current_points[1][0] += 10 current_points[2][0] += 10 current_points[3][0] -= 10 # Add the completed 1D array to our result collection list result_list.append(inter2d_result) # Convert the list of 1D arrays to a single 2D NumPy array result_array = np.array(result_list)
Key Notes
- The final
result_arraywill have a shape of(3, 10), exactly matching your desired structure[[inter2d_resultFIRST],[inter2d_resultSECOND],[inter2d_resultTHIRD]]. - Using a list for
result_listavoids the overhead of repeated NumPy array concatenations, which are less efficient than list appends. - We use
current_pointsinside the outer loop to reset the polygon coordinates cleanly without modifying a global variable repeatedly.
内容的提问来源于stack exchange,提问作者alx
相关产品推荐
相关产品推荐

