Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change only one column name in julia

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.

like image 654
Novic Avatar asked Oct 15 '20 12:10

Novic


People also ask

How do I rename a column in Julia?

To rename a column or columns, you need to use rename , or rename! . The difference is that rename creates a new data frame with the updated name(s) whereas rename! modifies the name(s) in-place. If you have a lot of columns to rename, it might be better to use a Dict .

How do you rename a column name?

To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.

How do I show all columns in Julia?

By default, Julia doesn't print all the rows and columns of a DataFrame because of obvious reasons like space and storage issues. But if you want to see all the rows and columns, it's possible using show() function with allrows & allcols arguments.


1 Answers

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     │
like image 114
Bogumił Kamiński Avatar answered Sep 20 '22 23:09

Bogumił Kamiński