Reputation: 351
If I have a dataframe like:
test = DataFrame(A = [1,2,3] , B= [4,5,6])
and I want to change only the name of A
, what can I do? I know that I can change the name of all columns together by rename!
but I need to rename one by one. The reason is that I'm adding new columns by hcat
in a loop and need to give them unique names each time.
Upvotes: 7
Views: 787
Reputation: 69949
Use the Pair
syntax:
julia> test = DataFrame(A = [1,2,3] , B= [4,5,6])
3×2 DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
julia> rename!(test, :A => :newA)
3×2 DataFrame
│ Row │ newA │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
julia> test
3×2 DataFrame
│ Row │ newA │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
With strings it is the same:
3×2 DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
julia> rename!(test, "A" => "newA")
3×2 DataFrame
│ Row │ newA │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
julia> test
3×2 DataFrame
│ Row │ newA │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
Upvotes: 11