朱莉娅-数据框-如何在by()中使用字符串进行自定义输出列命名 [英] Julia - dataframe - How to use string for custom output column naming in by()

查看:102
本文介绍了朱莉娅-数据框-如何在by()中使用字符串进行自定义输出列命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经熟悉Julia数据框模块. 我还没有找到一种方法要做的一件事是如何以编程方式为 分配by()操作结果的自定义列名.

I am getting familiar with Julia Dataframes module. One thing that I haven't found a way yet to do is how to assign programmatically a custom column name of the result of a by() operation.

因此,例如,我执行以下操作没有问题:

So for example I have no problem doing the following :

df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100))
by(df, :grp,result=(:x, :z)=>((x, y),) -> cov(x, y))

提供以下数据框

2×2 DataFrame
│ Row │ grp    │ result      │
│     │ String │ Float64     │
├─────┼────────┼─────────────┤
│ 1   │ b      │ -0.00622699 │
│ 2   │ a      │ -0.0303828  │

现在,我希望结果的命名依赖于代码的其他部分.所以我正在尝试做这件事

Now I would like the naming of the result to be dependent on some other part of my code. So i am trying things along this

resultColName="resultBis"
by(df, :grp,resultColName=(:x, :z)=>((x, y),) -> cov(x, y))

这给了我以下内容

2×2 DataFrame
│ Row │ grp    │ resultColName │
│     │ String │ Float64       │
├─────┼────────┼───────────────┤
│ 1   │ b      │ -0.00622699   │
│ 2   │ a      │ -0.0303828    │

这不起作用,因为我希望将结果列命名为"resultBis".我知道为什么会发生这种情况,但是目前是否有一种方法可以提供一个字符串来选择结果列的自定义名称?

Which doesn't work as I want the result column to be named 'resultBis'. I understand why this happens, but is there currently a way to provide a string to chose the custom name of the result column ?

我想使用宏可能是处理该问题的一种方式,对此我表示欢迎,但理想情况下,我想直接在DataFrames.jl中进行操作.欢迎任何帮助.谢谢

I imagine using macro could be one way to handle that and I would welcome that as an answer, but ideally I would like to do it directly within the DataFrames.jl. Any help is welcome. Thanks

推荐答案

julia> by(df, :grp, (; Symbol(resultColName)=>(:x, :z)=>((x, y),) -> cov(x, y)))
2×2 DataFrame
│ Row │ grp    │ resultBis  │
│     │ String │ Float64    │
├─────┼────────┼────────────┤
│ 1   │ a      │ -0.0110717 │
│ 2   │ b      │ 0.0102181  │

说明:

by接受NamedTuple作为第三个参数. 为了以编程方式创建它,我们使用(; :key => value)运算符.有关更多信息,请在Julia控制台中键入?NamedTuple.

by accepts a NamedTuple as the third parameter. In order to create it programmatically we use the (; :key => value) operator. For more information type ?NamedTuple into the Julia console.

这篇关于朱莉娅-数据框-如何在by()中使用字符串进行自定义输出列命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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