简体   繁体   中英

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. ie 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.

You can do it using List Comprehension:

result = [list(a[i,:]).count(a[i,0])-1 for i in range(a.shape[0])]
print(result)

This gives me:

[2, 3, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM