Change Column Names of a DataFrame - Previous methods don't work

Apologies for the repeat of old question, but most of the posts on this question seem to give outdated/nonfunctional solutions for defining or updating the column names of a DataFrame.

DataFrame(datamat,names)
or
names!(df,names)
rename!(df, names)

Aren’t working for me anymore.

I’ll keep searching, but what is the best approach?

Thanks in advance

PS In above ‘names is a vector of Symbols’. The statement worked in previous versions. Now I get the error

MethodError: no method matching rename!(::DataFrame, ::Array{Any,1})

1 Like
julia> using DataFrames

julia> df=DataFrame(c1=[1,2,3],c2=[3,4,5])
3×2 DataFrame
│ Row │ c1    │ c2    │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 3     │
│ 2   │ 2     │ 4     │
│ 3   │ 3     │ 5     │

julia> rename!(df,:c1 => :a)
3×2 DataFrame
│ Row │ a     │ c2    │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 3     │
│ 2   │ 2     │ 4     │
│ 3   │ 3     │ 5     │
4 Likes
julia> rename!(df,[:a,:b])
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 3     │
│ 2   │ 2     │ 4     │
│ 3   │ 3     │ 5     │

Thank you for this.

This latter is what I am after as my dataframe is too large to enumerate. I used this before with dataframe and Symbol Array, but now I get:

MethodError: no method matching rename!(::DataFrame, ::Array{Any,1})

[My name array contains only symbols]

help?> rename!
search: rename! rename propertynames

  rename!(df::AbstractDataFrame, vals::AbstractVector{Symbol};
          makeunique::Bool=false)
  rename!(df::AbstractDataFrame, vals::AbstractVector{<:AbstractString};
          makeunique::Bool=false)
...

Therefor an Array{Any,1} is not sufficient. It must be Array{Symbol,1} or Array{AbstractString,1}

Hi Thanks. I didn’t specify types, I just did what you did in your example
[:a,:b] etc. but using a loop. Do I need to explicitly specify type?

Try

symbols=Array{Symbol,1}(names)
rename!(df, symbols)
1 Like

Or show your code, so we can check where the Any comes from.
This

julia> [:a,:c]
2-element Array{Symbol,1}:
 :a
 :c

is an array of Symbols. No need to be explicit with types.

3 Likes

OK. Thanks. It seems that some of the column names weren’t Symbols and the previous version of DataFrames automatically converted them, the current one doesn’t.
Thanks Alot!

It would be great if we could rename DataFrame columns like this:


rename!(data, [:oldname1, :oldname2] =>  [:newname1, :newname2] )

rename! accepts a vector of pairs, so you can do this:

rename!(data, [:oldname1, :oldname2] .=>  [:newname1, :newname2])
5 Likes