Converting data types in a dataframe

Viewed 168

I want to change the datatypes of a column, I have tried doing that using the convert function to achieve this.

d = Dict("x" => [1,2,3,4,5],"y" => [6,7,8,9,10])    
df = DataFrame(d)

df[:,"x"] = convert.(Float64, df[:,"x"])

This still produces a dataframe with type Int64 for column x However using the dot notation to columns is successful,

df.x = convert.(Float64, df.x)

convert from type Int64 to Float64 successfully!

But in my case, I want to use for loop to convert data types in columns, so I am forced to use the first method (can think of a way to use the dot notation). Any ideas on how I can convert data types using a for a loop.

for nm in names(df)
    df[:, nm] = convert.(Float64, df[:,nm])
end
2 Answers

Try

df[!,"x"] = convert.(Float64, df[!,"x"])

Note the "!" in brackets - this gives you the actual DataFrame column (analogue to the dot notation), whereas ":" gives a copy of it.

you can alternatively write:

julia> df = DataFrame(rand(1:10, 3, 4), :auto)
3×4 DataFrame
 Row │ x1     x2     x3     x4
     │ Int64  Int64  Int64  Int64
─────┼────────────────────────────
   1 │     9      7      7     10
   2 │     2      5      7     10
   3 │     6      4      9      1

julia> transform!(df, names(df) .=> ByRow(Float64), renamecols=false)
3×4 DataFrame
 Row │ x1       x2       x3       x4
     │ Float64  Float64  Float64  Float64
─────┼────────────────────────────────────
   1 │     9.0      7.0      7.0     10.0
   2 │     2.0      5.0      7.0     10.0
   3 │     6.0      4.0      9.0      1.0
Related