Selecting rows from a data frame using multiple conditions

I want to select rows from a data frame using multiple conditions
This works with only one condition:

d_f = DataFrame(A=[ 1, 3, 4, 7, 9], B=["a", "c", "c", "D", "c"])
d_f[(d_f.B .== "c"), :]

Adding a second, this doesn’t work:

d_f[(d_f.A .== 3) & (d_f.B .== "c"), :]
# MethodError: no method matching &(::BitArray{1}, ::BitArray{1})

What do I need instead? Prior answers to this question appear to be outdated. Thanks.

You need to broadcast the &.

d_f[(d_f.A .== 3) .& (d_f.B .== "c"), :]

If you are using version 1.7, you can actually use the safer &&, which is actually control flow, rather than &, which is β€œbitwise OR”.

julia> d_f[(d_f.A .== 3) .&& (d_f.B .== "c"), :]
1Γ—2 DataFrame
 Row β”‚ A      B      
     β”‚ Int64  String 
─────┼───────────────
   1 β”‚     3  c

Finally, if you are using DataFramesMeta.jl, you can do

julia> using DataFramesMeta

julia> @rsubset(d_f, :A == 3, :B == "c")
1Γ—2 DataFrame
 Row β”‚ A      B      
     β”‚ Int64  String 
─────┼───────────────
   1 β”‚     3  c
6 Likes