首页 > 解决方案 > 有条件地添加列

问题描述

我正在尝试添加一个新列,其值取决于其他列。

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

条件哪里不对?

标签: julia

解决方案


这是你可以做到的(我使用randfrom 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"))

问题是你必须广播里面的操作transformetc.:b == 1总是false.

我还表明,在这种情况下,您可以使用简单地将结果转换为整数Intifelse如果您想要一些通用值,这很有用。

实际上在这种情况下可能@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

推荐阅读