使用 findall() 函数在具有多个条件的数据帧中搜索索引



inJulia 1.3

如何在具有多个条件的数据帧中搜索项目。下面是iris.csv数据集的示例(可在此处下载(

df = CSV.read(".../iris.csv");
df[1:6,:]
6 rows × 5 columns
sepal_length    sepal_width petal_length    petal_width species
Float64 Float64 Float64 Float64 String
1   5.1 3.5 1.4 0.2 setosa
2   4.9 3.0 1.4 0.2 setosa
3   4.7 3.2 1.3 0.2 setosa
4   4.6 3.1 1.5 0.2 setosa
5   5.0 3.6 1.4 0.2 setosa
6   5.4 3.9 1.7 0.4 setosa

假设我想选择sepal_length等于 5.1 的行的索引:

findall(df[:,1] .== 5.1)
9-element Array{Int64,1}:
1
18
20
22
24
40
45
47
99

现在与选择物种"setosa"的索引相同:

findall(df[:,5] .== "setosa")[1:10]
10-element Array{Int64,1}:
1
2
3
4
5
6
7
8
9
10

现在假设我想选择sepal_length等于 5.1 和物种"setosa"的行索引(我尝试了与R中函数which()类似的语法(:

findall(df[:,1] .== 5.1 & df[:,5] .== "setosa")
MethodError: no method matching &(::Float64, ::PooledArrays.PooledArray{String,UInt32,1,Array{UInt32,1}})
Closest candidates are:
&(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:529
Stacktrace:
[1] top-level scope at In[149]:1

我应该改用哪个命令?

你需要广播&运算符(注意&前的括号和点(,

findall((df[:,1] .== 5.1) .& (df[:,5] .== "setosa"))

但请注意,df[:,1] .== 5.1df[:,5] .== "setosa"都分配临时数组。考虑使用findall的版本,该版本将函数作为第一个参数,如下所示:

findall(x -> x.sepal.length == 5.1 && x.species == "setosa", eachrow(df))

最新更新