技术问询:统计两组数组相等数量及Numpy子数组差异数
Solution for Counting Equal and Differing Subarrays in NumPy Arrays
Got it, let's break down your two requirements clearly with actionable code and explanations.
1. Count the Number of Equal Subarrays
To count how many subarrays are identical between two NumPy arrays, we can leverage NumPy's vectorized operations to avoid manual looping:
- First, validate that the two input arrays have the same dimensions (comparing subarrays doesn't make sense if shapes don't match).
- Use
(a == b).all(axis=1)to create a boolean array where each entry isTrueif the corresponding subarrays inaandbare completely identical (theaxis=1flag checks equality across all elements in each subarray). - Sum the boolean array—since
Trueis treated as1andFalseas0, this gives the total count of equal subarrays.
Example code:
import numpy as np a = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]]) b = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,0,0]]) # Count equal subarrays if np.array_equal(a.shape, b.shape): equal_count = (a == b).all(axis=1).sum() print(f"Number of equal subarrays: {equal_count}") # Output: 4 else: print("Arrays have different shapes, cannot compare subarrays.")
2. Implement the diff_count Function
The diff_count function needs to count how many subarrays differ between the two input arrays, with no list comprehensions allowed. Here's a clean, efficient implementation using NumPy's built-in tools:
Approach
- First, check if the input arrays have matching shapes (raise an error if not, to avoid unexpected behavior).
- Use
(a != b).any(axis=1)to generate a boolean mask: each entry isTrueif the corresponding subarrays have at least one differing element. - Sum this mask to get the total number of differing subarrays.
Function Code
import numpy as np def diff_count(a, b): # Validate input shapes match if not np.array_equal(a.shape, b.shape): raise ValueError("Input arrays must have the same shape.") # Create mask for subarrays with any differences diff_mask = (a != b).any(axis=1) # Count the number of differing subarrays return diff_mask.sum() # Test with your example a = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]]) b = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,0,0]]) y = diff_count(a, b) print(y) # Output: 1
Explanation
(a != b)creates a boolean array of the same shape asa/b, marking every element where the two arrays differ..any(axis=1)collapses each subarray into a single boolean value:Trueif any element in the subarray differs,Falseotherwise..sum()counts the number ofTrueentries in the mask—this is exactly the number of subarrays that don't match betweenaandb.
内容的提问来源于stack exchange,提问作者Codevan
相关产品推荐
相关产品推荐

