iw2*_*rmb 5 syntactic-sugar julia
在以下情况下,有两种方法可以过滤DataFrame:
1. df = df[((df[:field].==1) | (df[:field].==2)), :]
2. df = df[[in(v, [1, 2]) for v in df[:field]], :]
Run Code Online (Sandbox Code Playgroud)
第二种方法比较慢,但适用于条件可变的一组值。我有没有想念的语法糖,所以我可以像第一种方法一样快但有一些类似in的构造吗?
julia> using DataFrames
Run Code Online (Sandbox Code Playgroud)
findin函数可能是完成任务的另一种方式:
julia> function t_findin(df::DataFrames.DataFrame)
df[findin(df[:A],[1,2]), :]
end
t3 (generic function with 1 method)
Run Code Online (Sandbox Code Playgroud)
数组理解:
julia> function t_compr(df::DataFrames.DataFrame)
df[[in(v, [1, 2]) for v in df[:A]], :]
end
t1 (generic function with 1 method)
Run Code Online (Sandbox Code Playgroud)
多重条件:
julia> function t_mconds(df::DataFrames.DataFrame)
df[((df[:A].==1) | (df[:A].==2)), :]
end
t2 (generic function with 1 method)
Run Code Online (Sandbox Code Playgroud)
测试数据
julia> df[:B] = rand(1:30,10_000_000);
julia> df[:A] = rand(1:30,10_000_000);
Run Code Online (Sandbox Code Playgroud)
检测结果
julia> @time t_findin(df);
0.489064 seconds (67 allocations: 19.340 MB, 0.49% gc time)
julia> @time t_mconds(df);
0.222389 seconds (106 allocations: 78.933 MB, 5.98% gc time)
julia> @time t_compr(df);
23.634846 seconds (100.00 M allocations: 2.563 GB, 1.47% gc time)
Run Code Online (Sandbox Code Playgroud)