Home > Software engineering >  Changing Julia dataframe column headers to lowercase?
Changing Julia dataframe column headers to lowercase?

Time:10-22

I am looking for a solution to change column's headers to lowercase.

Let's say, I have this dataframe:

df = DataFrame(TIME = ["2021-10-21","2021-10-22","2021-10-23"], 
               MQ2= [-1.1, -2, 1],
               MQ3=[-1, -1, 3.1],
               MQ8= [-1, -4.2, 2],
               )
>>>df
    TIME        MQ2     MQ3     MQ8
    String      Float64 Float64 Float64
1   2021-10-21  -1.1    -1.0    -1.0
2   2021-10-22  -2.0    -1.0    -4.2
3   2021-10-23  1.0     3.1     2.0

I want to change all of my column's headers, such as MQ2 to mq2. May be something like df.columns.str.lower() in Python.

Therefore, I can achieve this dataframe:

    time        mq2     mq3     mq8
    String      Float64 Float64 Float64
1   2021-10-21  -1.1    -1.0    -1.0
2   2021-10-22  -2.0    -1.0    -4.2
3   2021-10-23  1.0     3.1     2.0

CodePudding user response:

I would probably do the following:

julia> using DataFrames

julia> df = DataFrame(TIME = rand(5), MQ2 = rand(5), MQ3 = rand(5), MQ8 = rand(5));

julia> rename!(df, lowercase.(names(df)))
5×4 DataFrame
 Row │ time       mq2        mq3        mq8      
     │ Float64    Float64    Float64    Float64  
─────┼───────────────────────────────────────────
   10.0796718  0.997022   0.0838867  0.63886
   20.923035   0.904928   0.993185   0.36081
   30.392671   0.0577061  0.518647   0.81432
   40.0377552  0.506528   0.190017   0.488105
   50.828534   0.731297   0.383561   0.604786

Here I'm using the DataFrames rename function in its mutating version (hence the bang in rename!), with a vector of new column names as the second argument. The new vector is created by getting the current names using names(df), and then broadcasting the lowercase function across each element in that vector.

Note that rename! also accepts pairs of old/new names if you only want to rename specific columns, e.g. rename!(df, "TIME" => "time")

  • Related