How to change only one column name in julia
Asked Answered
H

1

7

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.

Horrific answered 15/10, 2020 at 12:25 Comment(0)
D
11

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     │
Dd answered 15/10, 2020 at 12:42 Comment(2)
Thank you, is there any way I can do this with strings instead of symbols?Horrific
Yes - it is exactly the same. I will update the answer.Osteotomy

© 2022 - 2024 — McMap. All rights reserved.