arrays - groupby() 在 julia 中使用两个数组?

标签 arrays group-by julia

我有两个相同维度的数组:

a1 = [1,1,3,4,6,6]
a2 = [1,2,3,4,5,6]

我想根据数组 a1 对它们进行分组,并获得每个组的数组 a2 的平均值。 我的输出来自数组a2,如下所述:

result:
1.5
3.0
4.0
5.5

请建议一种方法来完成这项任务。 谢谢!!

最佳答案

这是一个使用 DataFrames.jl 的解决方案:

julia> using DataFrames, Statistics

julia> df = DataFrame(a1 = [1,1,3,4,6,6], a2 = [1,2,3,4,5,6]);

julia> combine(groupby(df, :a1), :a2 => mean)
4×2 DataFrame
 Row │ a1     a2_mean
     │ Int64  Float64
─────┼────────────────
   1 │     1      1.5
   2 │     3      3.0
   3 │     4      4.0
   4 │     6      5.5

编辑:

这是时间安排(在 Julia 中您需要记住,第一次运行某个函数时必须对其进行编译,这需要时间):

julia> using DataFrames, Statistics

(@v1.6) pkg> st DataFrames # I am using main branch, as it should be released this week
      Status `D:\.julia\environments\v1.6\Project.toml`
  [a93c6f00] DataFrames v0.22.7 `https://github.com/JuliaData/DataFrames.jl.git#main`

julia> df = DataFrame(a1=rand(1:1000, 10^8), a2=rand(10^8)); # 10^8 rows in 1000 random groups

julia> @time combine(groupby(df, :a1), :a2 => mean); # first run includes compilation time
  3.781717 seconds (6.76 M allocations: 1.151 GiB, 6.73% gc time, 84.20% compilation time)

julia> @time combine(groupby(df, :a1), :a2 => mean); # second run is just execution time
  0.442082 seconds (294 allocations: 762.990 MiB)

请注意,例如类似数据上的 data.table(如果这是您的引用)明显较慢:

> library(data.table) # using 4 threads
> df = data.table(a1 = sample(1:1000, 10^8, replace=T), a2 = runif(10^8));
> system.time(df[, .(mean(a2)), by = a1])
   user  system elapsed 
   4.72    1.20    2.00 

关于arrays - groupby() 在 julia 中使用两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67174230/

相关文章:

PHP 解析错误 : syntax error, 意外 '$y6956096d' (T_VARIABLE)

arrays - Kotlin 不可变数组

SQL SUM Group by - 基于另一个表中的 'group'

julia - 将参数转换为复合类型

java - 将 C 语句转换为 Java (Array[][] != 0)

javascript - 如果数组中存在匹配文本,则突出显示页面上的文本

sql - 通过不正确分组来创建带有组的 View

mysql - 摘要查询返回重复值 MySQL

r - Julia pmap 性能

image - 如何使用 Julia 将数组保存到 RAM 中的 PNG 图像?