Julia: How to create a new column for each column of Number type?

Viewed 108

I wish to apply a function to all eltype(col) <: Number columns in a DataFrame and create a new column for each input column.

I am doing

f = identify # for example

function tmp(a)
    for n in names(a)
        if eltype(a[!, n]) <: Number
            a[!, n*"_binned"] = f(a[!, n])
        end
    end
    a
end

tmp(dataframe)

I feel there could be a more elegant way to do this in DataFrames.jl

1 Answers

I do not think we have anything much better now. You could write:

foreach(pairs(eachcol(a)) do (n, c)
    eltype(c) <: Number && (a[!, n * "_binned"] = bincut(c, target))
end

or

insertcols!(a, [n * "_binned" => bincut(c, target) for (n, c) in paris(eachcol(a)) if eltype(c) <: Number]..., copycols=false)

but this is essentially the same (I would probably use foreach, I am showing you insertcols! just to show the API. insertcols! is a bit safer as a[!, n*"_binned"] = bincut(a[!, n], target) will silently overwrite an existing column while insertcols! will error if you have column name duplicate).

Related