Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through columns in Julia

I want to add a number to all columns in a DataFrame. I am trying to use,

for i in names(df)
    df.i = df.i .+ 1
end

But this is giving error as ArgumentError: column name :i not found in the data frame

Any help is appreciated. Thanks in advance.

like image 240
lu5er Avatar asked Jan 01 '23 04:01

lu5er


1 Answers

Current advice for DataFrames.jl 1.0 or newer

Just write:

df .+= 1

to get what you want.

If you want to loop through columns it is also supported. Here are some examples:

for n in names(df)
    df[!, n] .+= 1
end

for col in eachcol(df)
    col .+= 1
end

Old advice for DataFrames.jl before 1.0 release

Currently you can use:

for i in axes(df, 2)
    df[i] .+= 1
end

or

for n in names(df)
    df[n] .+= 1
end

However, in the future you might need to write (there is a discussion if we should change the meaning of single argument indexing):

for col in eachcol(df, false)
    col .+= 1
end

or

foreach(x -> x .+= 1, eachcol(df, false))
like image 79
Bogumił Kamiński Avatar answered Feb 20 '23 21:02

Bogumił Kamiński