arrays - groupby() 在 julia 中使用两个数组?
问题描述
我有两个相同维度的数组:
a1 = [1,1,3,4,6,6]
a2 = [1,2,3,4,5,6]
而且我想将它们都相对于数组进行分组,并获得每个组a1
的数组平均值。a2
我的输出来自 array 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
推荐阅读
- pyspark - 带有数据框查询的 PySpark UDF 函数?
- python - 我正在尝试为 spacy 安装 en 但它给出了以下错误
- android - 在 Android Studio 中使用来自 SQLite 的数据填充 ExpandableListView
- javascript - 停止额外的间隔
- python - 如何处理 ML 分类中的字符串数据
- python-multiprocessing - python3中multiprocessing.Lock的共享字典
- javascript - setTimeout 在 iOS 中立即调用,同时启用模态视图,因此模态不会出现
- python - Tkinter Canvas.create_oval 不更新颜色
- perl - 通过 perl 更新查询时出现解析错误
- python - keras, scikit-learn, python, 二元分类混淆矩阵(我可能有bug)