Julia Community 🟣

Vinod V
Vinod V

Posted on • Edited on

Filtering Data Made Easy: Tips and Tricks in Julia

data_list = [1, 4, -5, 11, -7, 4, 3, -1]
Enter fullscreen mode Exit fullscreen mode

Values greater than zero

positives = [n for n in data_list if n > 0]
#positives = filter(>(0),data_list)
println(positives)
Enter fullscreen mode Exit fullscreen mode

Values less than zero

negatives = [n for n in data_list if n < 0]
#negatives = filter(<(0),data_list)
println(negatives)
Enter fullscreen mode Exit fullscreen mode

Negative values replaced with 0

neg_to_zero = [n > 0 ? n : 0 for n in data_list]
println(neg_to_zero)
Enter fullscreen mode Exit fullscreen mode

Positive values replaced with 0

pos_to_zero = [n < 0 ? n : 0 for n in data_list]
println(pos_to_zero)
Enter fullscreen mode Exit fullscreen mode

Filter to a range

rang = filter(x-> -3<x<1, data_list) #between -3 and 1
println(rang)
Enter fullscreen mode Exit fullscreen mode

Clamp between low and high values

clamp.(data_list,-2,4)
8-element Vector{Int64}:
  1
  4
 -2
  4
 -2
  4
  3
 -1
Enter fullscreen mode Exit fullscreen mode

Select values from a list based on values on some other list

addresses = [
    "5412 N Alappuzha",
    "5148 N Munnar", 
    "5800 E Kovalam",
    "2122 N Palakkad",
    "5645 N Wayanad",
    "1060 W Kumarakom",
    "4801 N Murukani",
    "1039 W Kollengode",
]

counts = [0, 3, 10, 4, 1, 7, 6, 1]

more5 = [n > 5 for n in counts]
a = addresses[more5]
a = [addresses[i] for i in eachindex(more5) if true == more5[i]]
a = [a for (a, c) in Iterators.zip(addresses, counts) if c > 5]
a = addresses[filter(i -> counts[i] > 5, 1:length(counts))]
a = addresses[counts .> 5]
println(a)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)