Number of each unique value in an array

Hi, I’m new to Julia and converting my existing python code to julia.

I often use np.unique with return_counts=True to get all unique values and the number of times each one appears in an array. I’m trying to find an alternative to this in Julia but I can’t find anything. I hope someone can help me here.

Thanks

You can use countmap from StatsBase.jl

julia> using StatsBase

julia> countmap([1, 1, 2, 3, 2, 1, 4, 1])
Dict{Int64, Int64} with 4 entries:
  4 => 1
  2 => 2
  3 => 1
  1 => 4
4 Likes

With no other packages, you could do something like

julia> a = [1, 2, 1, 3, 4, 5, 6, 6, 7]
9-element Vector{Int64}:
 1
 2
 1
 3
 4
 5
 6
 6
 7

julia> [count(==(element),a) for element in unique(a) ]
7-element Vector{Int64}:
 2
 1
 1
 1
 1
 2
 1

3 Likes