ジュリアで頻度を数える方法
説明
Juliaでオブジェクト内の要素の頻度を数えるときは関数 countmap または counts を使えばよい。どちらも パッケージ StatsBase を読み込む必要がある。
countmap はその名の通り要素とその個数の ペア を返す。入力対象が含む値についてのみ結果が得られる。
julia> countmap(x)
Dict{Int64, Int64} with 4 entries:
값1 => 값1의 빈도
값2 => 값2의 빈도
값3 => 값3의 빈도
값4 => 값4의 빈도
これに対して counts はまず出力がベクトルであり、整数に対してのみ使える。詳しくは下のコードを確認してくれ。
countmap
整数のベクトルでも、文字のベクトルでも、行列でも、文字列でも使える。
julia> x = rand(0:4, 100)
100-element Vector{Int64}:
0
4
⋮
4
1
julia> countmap(x)
Dict{Int64, Int64} with 5 entries:
0 => 28
4 => 20
2 => 13
3 => 16
1 => 23
julia> s = rand('a':'e', 100)
100-element Vector{Char}:
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
⋮
'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
julia> A = rand(0:4, (10,10))
10×10 Matrix{Int64}:
2 4 3 1 2 3 3 3 3 0
1 0 3 2 0 0 3 0 3 1
⋮ ⋮
2 0 1 3 4 4 2 0 4 4
1 4 4 4 2 1 2 1 0 4
julia> countmap(A)
Dict{Int64, Int64} with 5 entries:
0 => 19
4 => 24
2 => 15
3 => 22
1 => 20
julia> foo = "asdflk23f90cxnvjkcdsafalj;fdwaelkf"
"asdflk23f90cxnvjkcdsafalj;fdwaelkf"
julia> countmap(foo)
Dict{Char, Int64} with 18 entries:
'n' => 1
'f' => 5
';' => 1
⋮
'0' => 1
'2' => 1
'3' => 1
'v' => 1
counts
関数 counts は countmap と似ているが、結果が頻度のベクトルである点が異なる。ここで重要なのは、出力の第1成分が最小値の頻度、第2成分がその次の整数の頻度、というふうになっていることだ。
julia> x = [1, 1, 2, 2, 3]
5-element Vector{Int64}:
1
1
2
2
3
julia> counts(x)
3-element Vector{Int64}:
2 # x내 1의 빈도
2 # x내 2의 빈도
1 # x내 3의 빈도
julia> y = [3, 5, 5, 8, 8, 8]
6-element Vector{Int64}:
3
5
5
8
8
8
julia> counts(y)
6-element Vector{Int64}:
1 # y내 3의 빈도
0 # y내 4의 빈도
2 # y내 5의 빈도
0 # y내 6의 빈도
0 # y내 7의 빈도
3 # y내 8의 빈도
頻度を測る範囲を指定できる。
# 정수 k만 입력하면 범위 1:k 내의 빈도수를 반환
julia> counts(x, 5)
5-element Vector{Int64}:
2
2
1
0
0
julia> counts(x, 0:5)
6-element Vector{Int64}:
0
2
2
1
0
0
環境
- OS: Windows11
- Version: Julia 1.11.3, StatsBase v0.34.10
