作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想利用 DataFrames.jl
的 transform!
执行简单的 One-Hot 编码,但我没有成功。我使用以下数据框:
using DataFrames
df = DataFrame(
color = ["red", "green", "blue"],
x = [1, 2, 3]
)
# 3×2 DataFrame
# Row │ color x
# │ String Int64
# ─────┼───────────────
# 1 │ red 1
# 2 │ green 2
# 3 │ blue 3
我定义了一个简单的函数来返回编码矩阵:
function OneHotEncod(vec::Vector{String})
reduce(hcat, [vec .== i for i=vec])
end
然后,当我运行以下代码时,出现错误:
transform!(df, Cols(:color) => x -> OneHotEncod(x), renamecols=false)
ERROR: ArgumentError: Table returned, but a single output column was expected
错误很明显,但我想知道是否有任何方法可以在指定函数返回多个向量(如矩阵)时使用 transform!
?
附录:
OneHotEncod(df.color)
# 3×3 BitMatrix:
# 1 0 0
# 0 1 0
# 0 0 1
最佳答案
你只需要像这样指定输出有多个列:
julia> transform!(df, :color => OneHotEncod => AsTable)
3×5 DataFrame
Row │ color x x1 x2 x3
│ String Int64 Bool Bool Bool
─────┼────────────────────────────────────
1 │ red 1 true false false
2 │ green 2 false true false
3 │ blue 3 false false true
一个自然的选择是:
julia> transform!(df, [:color => ByRow(==(c)) => c for c in unique(df.color)])
3×8 DataFrame
Row │ color x x1 x2 x3 red green blue
│ String Int64 Bool Bool Bool Bool Bool Bool
─────┼─────────────────────────────────────────────────────────
1 │ red 1 true false false true false false
2 │ green 2 false true false false true false
3 │ blue 3 false false true false false true
然后您会自动设置信息性列名称。
关于dataframe - "ERROR: ArgumentError: Table returned but a single output column was expected"正在转换中!数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74945188/
我是一名优秀的程序员,十分优秀!