Julia - Frequency Tables to DataFrame

Viewed 851

I just found this package FreqTables, which allows one to easily construct frequency tables from DataFrames (I'm using DataFrames.jl).

The following lines of code return me a frequency table:

df = CSV.read("exampledata.csv")
freqtable(df,:col_name)

My question is how to turn the output into a dataframe again. The output from the frequency table function seems to be a NamedArray, which I haven't been able turn into a dataframe.

2 Answers

This does not directly answer your question, but freq tables you can alternatively just write:

julia> df = DataFrame(A = [2,2,2,2,5,5,5])
7×1 DataFrame
│ Row │ A     │
│     │ Int64 │
├─────┼───────┤
│ 1   │ 2     │
│ 2   │ 2     │
│ 3   │ 2     │
│ 4   │ 2     │
│ 5   │ 5     │
│ 6   │ 5     │
│ 7   │ 5     │

julia> combine(groupby(df, :A), nrow => :Freq)
2×2 DataFrame
│ Row │ A     │ Freq  │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 2     │ 4     │
│ 2   │ 5     │ 3     │

to get the same

I found this solution to work for me:

using DataFrames, FreqTables
ft = freqtable(df, :A)
df = DataFrame(A = [2,2,2,2,5,5,5], B = [1,1,1,6,6,6,6])
DataFrame(A = names(ft)[1], Freq = ft)

Result:

2×2 DataFrame
│ Row │ A     │ Freq  │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 2     │ 4     │
│ 2   │ 5     │ 3     │
Related