'Count number of elements in each row equal to the first element in each row
a = np.array((['1', '1', '1', '2'],
['3', '3', '3', '3'],
['2', '1', '1', '2'],
['1', '3', '1', '2']))
I am looking for a way (rather than iterating over the array) to count the number of elements in each row that are the equal to the first element of the row. i.e. in the first row, the first element is '1' and there are 2 other occurrences of this value. The final result should be:
result = [2, 3, 1, 1]
My array can be quite large so iterating over each row will be slow.
Solution 1:[1]
Compare to the slice a[..., 0]. Append a new axis to make it the correct dimensions again.
result = (a == a[..., 0][..., np.newaxis]).sum(axis=-1) - 1
The ... ensure that this works for arrays of any dimension, whereas using : only works for 2D.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
