Julia:为 DataFrame 的 y 列中的每个唯一值创建 x 列的汇总值 [英] Julia: Create summary values for column x for each unique value in column y of DataFrame

查看:17
本文介绍了Julia:为 DataFrame 的 y 列中的每个唯一值创建 x 列的汇总值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 DataFrame 的列 x 应用一些函数,例如均值和方差,以便为列 y 中的每个唯一值.我可以想象构建一个循环,手动将 DataFrame 子集化以完成我的目的,但我试图不为可能是常见功能的东西重新发明轮子.

I would like to apply some functions such as mean and variance to column x of my DataFrame for each unique value in column y. I can imagine building a loop that manually subsets the DataFrame to accomplish my end but I am trying not to reinvent the wheel for something which is likely a common feature.

using DataFrames
mydf = DataFrame(y = [randstring(1) for i in 1:1000], x = rand(1000))
# I could imagine a function that looks like:
apply(function = mean, across = mydf[:x], by = mydf[:y])

推荐答案

你说得对,这很常见.看看 文档中的 split-apply-combine 章节.这里有几种方法:您可以使用更通用的 by 函数来准确指定要操作的列,或者您可以使用方便的 aggregate 函数来使用所有其他列并自动合理地命名它们:

You're right this is very common. Take a look at the split-apply-combine chapter in the documentation. There are several approaches here: you can either use the more general by function to specify exactly what columns you want to operate over, or you can use the handy aggregate function to use all the other columns and automatically name them sensibly:

julia> aggregate(mydf, :y, mean)
62×2 DataFrames.DataFrame
│ Row │ y   │ x_mean   │
├─────┼─────┼──────────┤
│ 1   │ "0" │ 0.454196 │
│ 2   │ "1" │ 0.541434 │
│ 3   │ "2" │ 0.36734  │
⋮

这篇关于Julia:为 DataFrame 的 y 列中的每个唯一值创建 x 列的汇总值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆