【发布时间】:2021-03-03 09:21:27
【问题描述】:
我想替换管道中的缺失值。我知道如何在管道外进行操作 (see this post for more on that)。
julia> df = DataFrame(:b => [2, 3], :a => [missing, "treatment"])
2×2 DataFrame
│ Row │ b │ a │
│ │ Int64 │ String? │
├─────┼───────┼───────────┤
│ 1 │ 2 │ missing │
│ 2 │ 3 │ treatment │
julia> df.a = replace(df.a, missing => "control") # works like expected
julia> @pipe df |>
replace(_.a, missing => "control") |>
select(_, :a, :b) # error because replace doesn't return a DataFrame.
我尝试编写转换函数,但 ismissing() 在这种情况下不起作用。我认为这是因为它得到了一列而不是单独的值。但是ismissing.() 也不起作用。有人知道如何使这种转变发挥作用吗?
julia> ismissing(df.a[1])
true
julia> @pipe df |>
DataFrames.transform(_, :a => x -> ismissing(x) ? "control" : x)
2×3 DataFrame
│ Row │ b │ a │ a_function │
│ │ Int64 │ String? │ String? │
├─────┼───────┼───────────┼────────────┤
│ 1 │ 2 │ missing │ missing │
│ 2 │ 3 │ treatment │ treatment │
julia> @pipe df |>
DataFrames.transform(_, :a => x -> ismissing(x) ? x : "control" )
2×3 DataFrame
│ Row │ b │ a │ a_function │
│ │ Int64 │ String? │ String │
├─────┼───────┼───────────┼────────────┤
│ 1 │ 2 │ missing │ control │
│ 2 │ 3 │ treatment │ control │
julia> @pipe df |>
DataFrames.transform(_, :a => (x -> ismissing.(x) ? "control" : x) )
ERROR: TypeError: non-boolean (BitArray{1}) used in boolean context
附:
我知道我可以使用@transform 宏,但我觉得它不是很优雅。我认为这种替换应该可以在一行代码中实现。
julia> @pipe df |>
@transform(_, :a, x = replace(:a, missing => "control")) |>
select(_, Not(:a)) |>
rename(_, :x => :a)
2×2 DataFrame
│ Row │ b │ a │
│ │ Int64 │ String │
├─────┼───────┼───────────┤
│ 1 │ 2 │ control │
│ 2 │ 3 │ treatment │
【问题讨论】: