Number of unique elements per row in a NumPy array

后端 未结 4 622
执念已碎
执念已碎 2021-01-15 00:41

For example, for

a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])

I want to get

[2, 2, 3]

Is there a way

4条回答
  •  生来不讨喜
    2021-01-15 01:08

    This solution via np.apply_along_axis isn't vectorised and involves a Python-level loop. But it is relatively intuitive using len + np.unique functions.

    import numpy as np
    from toolz import compose
    
    a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
    
    np.apply_along_axis(compose(len, np.unique), 1, a)    # [2, 2, 3]
    

提交回复
热议问题