Iterating over a column and changing its value according to a condition

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
r.Values[r.Values.<0.030] .= 0.030
r.Values[r.Values.>0.95] .= 0.95

Plus: replaces in place

Minus: does two passes

coerce(x) = x<0.030 ? 0.030 : x>0.95 ? 0.95 : x
r.Values .= coerce.(r.Values)

Plus: okay this is just plain better

coerce(x) = min(0.95, max(0.030, x))

Last offer.

1 Like

there is a function that does exactly that: clamp
So you can do:

transform(df, :Values => x -> clamp.(x, 0.025, 0.95))
2 Likes