How to use Regex with CategoricalArrays in Julia?

Viewed 24

I was discovering CategoricalArrays when I realize I couldn't filter this vector with Regex. I looked to the exported functions and I found the unwrap function and it seemed to work. Why shouldn't this work directly? is there another form to work with?

using CategoricalArray;DataFrame;
df=DataFrame(x=1:6,
fruit=categorical(vcat(repeat(["banana"],3),repeat(["pineapple"],3))));

df[occursin.(r"ple",df.fruit),:] #you'll get an error
1 Answers

Use unwrap:

julia> using CategoricalArrays, DataFrames

julia> df=DataFrame(x=1:6, fruit=categorical(vcat(repeat(["banana"],3),repeat(["pineapple"],3))))
6×2 DataFrame
 Row │ x      fruit
     │ Int64  Cat…
─────┼──────────────────
   1 │     1  banana
   2 │     2  banana
   3 │     3  banana
   4 │     4  pineapple
   5 │     5  pineapple
   6 │     6  pineapple

julia> df[occursin.(r"ple", unwrap.(df.fruit)),:]
3×2 DataFrame
 Row │ x      fruit
     │ Int64  Cat…
─────┼──────────────────
   1 │     4  pineapple
   2 │     5  pineapple
   3 │     6  pineapple

With CategoricalArrays.jl it is important to understand that the elements of CategoricalArray are CategoricalValue. These objects "carry over" the categorical nature of the data. If you want to get the underlying raw value you need to use unwrap.

Related