Renaming multiple columns in Julia DataFrames

208 views Asked by At

I have the following Julia Daataframe;

data_test = DataFrame(Time = 1:2, X1 = [0,1], X2 = [10,5])

And I have a list of names as follows;

technology = ["oil", "gas"]

How do I rename columns X1 and X2 using the list (excluding Time column). I can do it manually, however, this is not an efficient option to rename hundreds of columns. So, essentially, I'm what I'm looking for is a way to map the list of names to the columns. Any efficient solution is highly appreciated.

2

There are 2 answers

1
Amon On

You can try something like this (works for Julia 1.7.2):

data_test = DataFrame(Time = 1:2, X1 = [0,1], X2 = [10,5])
new_names = Dict(
    :X1=>"oil",
    :X2=>"gas",
)
rename!(data_test, new_names)
0
M.B On

A solution I received from JuliaDiscourse.

rename!(data_test, ["X$i" => tech for (i, tech) in enumerate(technology)])