Number of unique elements per row in a NumPy array

后端 未结 4 531
执念已碎
执念已碎 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 00:54

    Are you open to considering pandas? Dataframes have a dedicated method for this

    >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
    >>> df = pd.DataFrame(a.T)
    >>> print(*df.nunique())
    2 2 3
    

提交回复
热议问题