如何编写代码将多维数组中满足条件的索引及后续元素置零并解决numpy属性错误
Solution to Fix Your Array Zeroing Logic
First, let's break down the issues in your original code:
numpy.ndarray(even withdtype="object") doesn't have anindex()method—this is exactly why you're hitting theAttributeError.- Using
l.index(i)is bug-prone: if a row has duplicate values, it will return the first occurrence ofiinstead of the current position you're checking. - You weren't breaking the inner loop after finding the first condition match, which leads to unnecessary (and potentially incorrect) repeated zeroing.
Here's the corrected code that addresses all these issues and produces your expected output:
import numpy as np a = np.array([[12,45,50,-600,30,23.2,232,-44,12], [45,50,60,30,23.2,232,-44,12,23], [50,60,30,23.2,232,-44,12,34,12], [60,30,23.2,232,-44,12,120,3,4], [-300,23.2,232,-44,12,23,23,2,12], [23.2,-232,-44,12,34,1,2,300.3,5]], dtype='object') b = np.array([-12.4,-13.4,-44,-100,-6.3,-11,-10,-1.1,-0.3]) # Iterate over each row in array a for row_idx, row in enumerate(a): # Check each element and its index in the current row for counter, val in enumerate(row): # Match the two conditions from your requirement if val <= 0 or b[counter] <= -100: # Zero out all elements from current index onwards row[counter:] = [0] * len(row[counter:]) # Break the inner loop immediately—we only need the first matching position break # Print the result as a list (matches your expected output format) print(a.tolist())
Key Fixes & Improvements:
- Replaced
l.index(i)withcounter: Since we're already usingenumerate()to get the current element's index, we can directly usecounterto target the correct position—no need to search for the index. - Added
breakafter zeroing: Once we find the first position that meets either condition, we stop checking the rest of the row (since those elements will already be zeroed out). - Adjusted condition to
val <= 0: Your requirement specifies "negative or zero"—the original code only checked for negative values (i < 0), so we fixed that to include zero.
Bonus: Faster Vectorized Approach (For Uniform Row Lengths)
Since your rows all have the same length, you can ditch the object dtype and use numpy's vectorized operations for better performance (especially with large datasets):
import numpy as np # Convert to float64 array (works because all rows are same length) a = np.array([[12,45,50,-600,30,23.2,232,-44,12], [45,50,60,30,23.2,232,-44,12,23], [50,60,30,23.2,232,-44,12,34,12], [60,30,23.2,232,-44,12,120,3,4], [-300,23.2,232,-44,12,23,23,2,12], [23.2,-232,-44,12,34,1,2,300.3,5]], dtype=np.float64) b = np.array([-12.4,-13.4,-44,-100,-6.3,-11,-10,-1.1,-0.3], dtype=np.float64) for row_idx in range(a.shape[0]): # Create a boolean mask for the two conditions condition_mask = (a[row_idx] <= 0) | (b <= -100) # Find the first position where the condition is True first_zero_pos = np.argmax(condition_mask) # If any position meets the condition, zero out from that point onward if condition_mask[first_zero_pos]: a[row_idx, first_zero_pos:] = 0 print(a.tolist())
This approach leverages numpy's optimized C-backed operations instead of Python loops, making it much faster for large arrays.
内容的提问来源于stack exchange,提问作者georgehere
相关产品推荐
相关产品推荐

