Since you’re in control of varlist, you could simplify this at least once 
by using symbols from the beginning. Next, you can use the symbol function 
and a different overload of string instead of convert to make the 
concat-convert operation a little less ugly:

julia> using DataFrames

julia> df = DataFrame(A = rand(5), B = rand(5), C = rand(5), D = rand(5))
5x4 DataFrames.DataFrame
| Row | A        | B        | C        | D        |
|-----|----------|----------|----------|----------|
| 1   | 0.550768 | 0.464531 | 0.141101 | 0.754492 |
| 2   | 0.629269 | 0.100223 | 0.981175 | 0.035041 |
| 3   | 0.26019  | 0.962588 | 0.948283 | 0.51513  |
| 4   | 0.755892 | 0.202503 | 0.727609 | 0.255172 |
| 5   | 0.28018  | 0.328776 | 0.684717 | 0.502154 |

julia> varlist = [:B,:C]
2-element Array{Symbol,1}:
 :B
 :C

julia> for i in eachindex(varlist)
           rename!(df, varlist[i], symbol(string(varlist[i], i)))
       end

julia> df
5x4 DataFrames.DataFrame
| Row | A        | B1       | C2       | D        |
|-----|----------|----------|----------|----------|
| 1   | 0.550768 | 0.464531 | 0.141101 | 0.754492 |
| 2   | 0.629269 | 0.100223 | 0.981175 | 0.035041 |
| 3   | 0.26019  | 0.962588 | 0.948283 | 0.51513  |
| 4   | 0.755892 | 0.202503 | 0.727609 | 0.255172 |
| 5   | 0.28018  | 0.328776 | 0.684717 | 0.502154 |

I usually think of symbols as "strings with some constraints", and using 
one instead of the other then becomes quite trivial, conceptually.

// T

On Friday, May 8, 2015 at 8:27:18 PM UTC+2, Nils Gudat wrote:

I've been trying to rename a bunch of columns in a DataFrame and as a 
> former pandas user am a bit thrown off by the way columns are accessed 
> using symbols. 
> Let's say I have a list of column names (strings) which I want to all give 
> the same name with ascending integers at the end. After a few unsuccesful 
> attempts, I came up with the following, but I feel like there has to be a 
> less ugly way of doing this:
>
> df = DataFrame(A = rand(5), B = rand(5), C = rand(5), D = rand(5))
> varlist = ["B", "C"]
>
> for i = 1:length(varlist)
>   rename!(df, convert(Symbol, varlist[i])), convert(Symbol, 
> "column_"*string(i))
> end
>
​

Reply via email to