Very creative maxpooling, don't konw how to implement

suppost I have a tensor H * 3, and it’s cooresponding ids: H * 1, ids[i] means tensor[i,:] belong to one block, the numbers in ids can have same value, for example, ids = [0,0,0,1,2,3,5,5], now I want do maxpooling for those tensor[i,:] belong to same id.

For example:
tensor : 4 * 3
1 1 1
2 2 2
3 3 3
4 4 4

ids:
0
0
0
1

now, do maxpooling, 1 1 1, 2 2 2, 3 3 3 do maxpooling , get 3 3 3 , 4 4 4 do maxpooling, get 4 4 4

use for loop is too slow, my H * 3, H is generally 20000