Changing values in DataFrame row according to conditions

Viewed 271

I have a .csv file with a column named "Values"

ID  Values
0   0.201915
1   0.441945
2   0.001931
3   0.221311
4   0.303101

this .csv file has 180900 rows. I need to change the Values according to a condition, like:

if [value] < 0.030 then [value] = 0.030 else [value] AND if [value] > 0.95 then [value] = 0.95 else [Value]

What i tried so far: (only checking values lower than 0.025 first)

    i = 1
    for r in eachrow(df)
      global i
      if r.Values < 0.025
         r.Values = 0.025
      i =1+1
    end

Can someone help me?

1 Answers

Just do

df.Values = min.(max.(0.3, df.Values), 0.95);

And here is a full code with your data:

julia> df = CSV.read(IOBuffer("""ID  Values
              0   0.201915
              1   0.441945
              2   0.001931
              3   0.961311
              4   0.303101"""),DataFrame, delim=" ", ignorerepeated=true)
5×2 DataFrame
 Row │ ID     Values
     │ Int64  Float64
─────┼─────────────────
   1 │     0  0.201915
   2 │     1  0.441945
   3 │     2  0.001931
   4 │     3  0.961311
   5 │     4  0.303101

julia> max(3,4)
4

julia> df.Values = min.(max.(0.3, df.Values), 0.95);

julia> df
5×2 DataFrame
 Row │ ID     Values
     │ Int64  Float64
─────┼─────────────────
   1 │     0  0.3
   2 │     1  0.441945
   3 │     2  0.3
   4 │     3  0.95
   5 │     4  0.303101

As suggested by Bogumil you can try also clamp which is slightly faster:

df.Values = clamp.(df.Values, 0.3, 0.95)
Related