Julia: how to select all columns from a DataFrame satisfying a certain condition?

Viewed 68

Say I want to select all float columns in the dataset. Is there a more convenient syntax than

cols = [eltype(col) <: Float64 for col in eachcol(df)]

select(df, cols)

?

2 Answers

You can vectorize the list comprehension:

select(df, eltype.(eachcol(df)) .<: Float64)

Example of using vectorization:

julia> df = [[1,2,3], ['f', 'j'], [1.2, 2.3]]
3-element Vector{Vector{T} where T}:
 [1, 2, 3]
 ['f', 'j']
 [1.2, 2.3]

julia> eltype.(df)
3-element Vector{DataType}:
 Int64
 Char
 Float64

julia> eltype.(df) .<: Float64
3-element BitVector:
 0
 0
 1

Aternatively you can write:

select(df, names(df, Float64))

or

df[:, names(df, Float64)]
Related