Incorrect results for assigning filtered values within the same column

Viewed 46

I want to filter values within a column and assign a value to the filtered results. However I get incorrect results, In this case, I want to assign a value of 1 to values between 20 and 30 and the rest 0. But I get 1 for all values. Any ideas why?

df = DataFrame(
    Dict(
        "time" => collect(1:10),
        "cost" => [23,99,81,56,28,31,98,34,21,17]
    )
)

df.cat = missing
df.cat = ifelse.(df.cost .> 20 .& df.cost .< 30, 1,0)

out:

enter image description here

2 Answers

Problem is that you need to put parenthesis around the df.cost .> 20 and df.cost .< 30 part:

julia> df = DataFrame(
           Dict(
               "time" => collect(1:10),
               "cost" => [23,99,81,56,28,31,98,34,21,17]
           )
       );

julia> df.cat = ifelse.((df.cost .> 20) .& (df.cost .< 30), 1, 0);

julia> df
10×3 DataFrame
 Row │ cost   time   cat
     │ Int64  Int64  Int64
─────┼─────────────────────
   1 │    23      1      1
   2 │    99      2      0
   3 │    81      3      0
   4 │    56      4      0
   5 │    28      5      1
   6 │    31      6      0
   7 │    98      7      0
   8 │    34      8      0
   9 │    21      9      1
  10 │    17     10      0

You are hit by operator precedence problem. This is a fix:

df.cat = ifelse.((df.cost .> 20) .& (df.cost .< 30), 1, 0)

(note additional parentheses around conditions)

As a side note consider upgrading DataFrames.jl to the latest version, as clearly you are not on 0.22 release, as df.cat = missing operation has been deprecated over 2 years ago and currently we print data frames more compactly to improve display experience.

Related