Renaming Column Names of a DataFrame in Julia
Overview
To rename columns, you can use the rename!()
function1.
You can rename them all at once by providing a list of strings, or individually.
Code
using DataFrames
df = DataFrame(rand(1:9, 10, 3), :auto)
rename!(df, ["X", "Y", "Z"])
rename!(df, :X => :A)
When executed, it first creates the following dataframe:
julia> df = DataFrame(rand(1:9, 10, 3), :auto)
10×3 DataFrame
Row │ x1 x2 x3
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 2 3 6
2 │ 9 2 4
3 │ 3 3 4
4 │ 3 3 3
5 │ 9 1 6
6 │ 3 1 5
7 │ 4 8 4
8 │ 9 8 4
9 │ 4 6 1
10 │ 1 9 7
Renaming All at Once
julia> rename!(df, ["X", "Y", "Z"])
10×3 DataFrame
Row │ X Y Z
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 2 3 6
2 │ 9 2 4
3 │ 3 3 4
4 │ 3 3 3
5 │ 9 1 6
6 │ 3 1 5
7 │ 4 8 4
8 │ 9 8 4
9 │ 4 6 1
10 │ 1 9 7
Just provide a list of strings.
Renaming One by One
julia> rename!(df, :X => :A)
10×3 DataFrame
Row │ A Y Z
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 2 3 6
2 │ 9 2 4
3 │ 3 3 4
4 │ 3 3 3
5 │ 9 1 6
6 │ 3 1 5
7 │ 4 8 4
8 │ 9 8 4
9 │ 4 6 1
10 │ 1 9 7
This method, which is rarely seen in other languages, involves prefixing column names with :
and mapping them with =>
. In Julia, a variable that starts with :
is a Symbol.
Environment
- OS: Windows
- julia: v1.6.2