How to get dtypes of columns in julia dataframe

Viewed 930

How to get dtypes of all columns and particular column(s) in julia. To be specific what is the pandas equivalent of df.dtypes in julia?

For example, I have a df like below,

│ Row │ Id    │ name   │ item location │
│     │ Int64 │ String │ String        │
├─────┼───────┼────────┼───────────────┤
│ 1   │ 1     │ A      │ xyz           │
│ 2   │ 2     │ B      │ abc           │
│ 3   │ 3     │ C      │ def           │
│ 4   │ 4     │ D      │ ghi           │
│ 5   │ 5     │ E      │ xyz           │
│ 6   │ 6     │ F      │ abc           │
│ 7   │ 7     │ G      │ def           │
│ 8   │ 8     │ H      │ ghi           │
│ 9   │ 9     │ I      │ xyz           │
│ 10  │ 10    │ J      │ abc           │

Expected output:

{'id':  Int64, 'name': String, 'item location': String}

How to get dtypes, i.e., Int64 │ String │ String in Julia?

2 Answers

You have specified two different expected outputs so I show here how to get both:

julia> df = DataFrame("Id" => 1, "name" => "A", "item_location" => "xyz")
1×3 DataFrame
│ Row │ Id    │ name   │ item_location │
│     │ Int64 │ String │ String        │
├─────┼───────┼────────┼───────────────┤
│ 1   │ 1     │ A      │ xyz           │

julia> eltype.(eachcol(df))
3-element Array{DataType,1}:
 Int64
 String
 String

julia> Dict(names(df) .=> eltype.(eachcol(df)))
Dict{String,DataType} with 3 entries:
  "Id"            => Int64
  "name"          => String
  "item_location" => String

additionally, if you wanted to store the result in a DataFrame instead of a Dict you can write (see mapcols documentation here):

julia> mapcols(eltype, df)
1×3 DataFrame
│ Row │ Id       │ name     │ item_location │
│     │ DataType │ DataType │ DataType      │
├─────┼──────────┼──────────┼───────────────┤
│ 1   │ Int64    │ String   │ String        │

And if you would want to have a NamedTuple storing this information write (the documentation of Tables.columntable is here):

julia> map(eltype, Tables.columntable(df))
(Id = Int64, name = String, item_location = String)

(in this case note that for very wide tables this might have some extra compilation cost as each time you call it you potentially get a new type of NamedTuple)

You can also use describe(df) which is a catchall for learning about the columns in your data frame.

Related