Home > Enterprise >  Order columns alphabetically in dataframe Julia
Order columns alphabetically in dataframe Julia

Time:01-01

I have a dataframe like this:

using DataFrames

df = DataFrame(C = [1,2,3],
               A = [1,1,1], 
               B = [3,2,1])
3×3 DataFrame
 Row │ C      A      B     
     │ Int64  Int64  Int64 
─────┼─────────────────────
   1 │     1      1      3
   2 │     2      1      2
   3 │     3      1      1

I would like to alphabetically order these columns which would be of course: A,B and C. How can we do this in a dataframe Julia? It could be more than 3 columns. In R we could use the order function.

CodePudding user response:

The first method I came up with is:

julia> select(df, sort(propertynames(df)))
3×3 DataFrame
 Row │ A      B      C     
     │ Int64  Int64  Int64 
─────┼─────────────────────
   1 │     1      3      1
   2 │     1      2      2
   3 │     1      1      3

and to mutate df into ordered form:

select!(df, sort(propertynames(df)))

CodePudding user response:

How about using names with sortperm

julia> df[:, sortperm(names(df))]
3×3 DataFrame
 Row │ A      B      C     
     │ Int64  Int64  Int64 
─────┼─────────────────────
   1 │     1      3      1
   2 │     1      2      2
   3 │     1      1      3
  • Related