Home > Software engineering >  Get Column Types of Julia DataFrames
Get Column Types of Julia DataFrames

Time:11-23

How can I get the column types of a Julia DataFrame?

using DataFrames

df = DataFrame(a = 1:4, b = ["a", "b", "c", "d"])

4×2 DataFrame
 Row │ a      b      
     │ Int64  String 
─────┼───────────────
   1 │     1  a
   2 │     2  b
   3 │     3  c
   4 │     4  d

CodePudding user response:

Some additional options (keeping the result in a data frame):

julia> mapcols(eltype, df)
1×2 DataFrame
 Row │ a         b
     │ DataType  DataType
─────┼────────────────────
   1 │ Int64     String

julia> mapcols(typeof, df)
1×2 DataFrame
 Row │ a              b
     │ DataType       DataType
─────┼───────────────────────────────
   1 │ Vector{Int64}  Vector{String}

julia> describe(df, :eltype)
2×2 DataFrame
 Row │ variable  eltype
     │ Symbol    DataType
─────┼────────────────────
   1 │ a         Int64
   2 │ b         String

EDIT: in describe you get the element type of a column with stripped Missing - I have forgotten to add this comment earlier.

CodePudding user response:

For each column I can get the element type like this:

eltype.(eachcol(df))

The same can be achieved (and I like this even better) with

df |> eachcol .|> eltype

2-element Vector{DataType}:
 Int64
 String

The actual type of the column can be retrieved with

df |> eachcol .|> typeof

2-element Vector{DataType}:
 Vector{Int64} (alias for Array{Int64, 1})
 Vector{String} (alias for Array{String, 1})
  • Related