julia - 有条件地添加列
问题描述
我正在尝试添加一个新列,其值取决于其他列。
using DataFrames, DataFramesMeta
df = DataFrame(a = 1:10,
b = StatsBase.sample([0, 1], 10, replace = true),
c = StatsBase.sample([0, 1], 10, replace = true),
d = StatsBase.sample([0, 1], 10, replace = true))
@linq df |>
transform(e = ifelse.(:b == 1 || :c == 1 || :d == 1, 1, 0))
但这不能正确评估:
a b c d e
1 1 0 1 1 0
2 2 1 0 1 0
3 3 0 0 0 0
4 4 1 1 0 0
5 5 1 0 0 0
6 6 0 1 0 0
7 7 0 0 0 0
8 8 1 0 1 0
9 9 1 0 1 0
10 10 0 1 1 0
条件哪里不对?
解决方案
这是你可以做到的(我使用rand
from Base 来生成数据,因为在这种情况下就足够了):
using DataFrames, DataFramesMeta
df = DataFrame(a = 1:10, b = rand([0, 1], 10),
c = rand([0, 1], 10), d = rand([0, 1], 10))
@linq df |>
transform(e = Int.((:b .== 1) .| (:c .== 1) .| (:d .== 1)))
@linq df |>
transform(e = ifelse.((:b .== 1) .| (:c .== 1) .| (:d .== 1), "yes", "no"))
问题是你必须广播里面的操作transform
etc.:b == 1
总是false
.
我还表明,在这种情况下,您可以使用简单地将结果转换为整数Int
,ifelse
如果您想要一些通用值,这很有用。
实际上在这种情况下可能@byrow!
更简单:
@byrow! df begin
@newcol e::Vector{Int}
:e = :b == 1 || :c == 1 || :d == 1 ? 1 : 0
end
编辑。在 DataFramesMeta.jl 0.10 下,它将是:
julia> using DataFrames, DataFramesMeta
julia> df = DataFrame(a = 1:10, b = rand([0, 1], 10),
c = rand([0, 1], 10), d = rand([0, 1], 10))
10×4 DataFrame
Row │ a b c d
│ Int64 Int64 Int64 Int64
─────┼────────────────────────────
1 │ 1 0 1 0
2 │ 2 0 0 0
3 │ 3 0 1 1
4 │ 4 0 1 0
5 │ 5 1 1 1
6 │ 6 1 1 1
7 │ 7 0 1 1
8 │ 8 0 0 0
9 │ 9 1 0 0
10 │ 10 0 1 0
julia> @rtransform(df, :e = Int(:b == 1 || :c == 1 || :d == 1))
10×5 DataFrame
Row │ a b c d e
│ Int64 Int64 Int64 Int64 Int64
─────┼───────────────────────────────────
1 │ 1 0 1 0 1
2 │ 2 0 0 0 0
3 │ 3 0 1 1 1
4 │ 4 0 1 0 1
5 │ 5 1 1 1 1
6 │ 6 1 1 1 1
7 │ 7 0 1 1 1
8 │ 8 0 0 0 0
9 │ 9 1 0 0 1
10 │ 10 0 1 0 1
推荐阅读
- c# - Win10 和 MacOS 的 GUI 计算器?
- php - 如何检查列是否等于一个值,如果为真则做某事?
- python - 当并非在所有情况下都需要所有字段时,如何为用户输入构建 django 模型
- github-for-windows - Github...当我在 github 上发布我的网站时,背景图片不显示
- c++ - 如何为动作识别项目编写一个 vs 多类 SVM 代码
- websocket - 服务器广播到多个 websocket。有些更快?
- c# - 将枚举值和名称序列化为 JSON
- lua - 需要帮助理解表的元方法被设置为该表
- java - 在docker中运行spring boot webapp时,我应该使用“-server”java标志吗?
- ruby-on-rails - 关于belong_to、has_one、has_many 的困惑