gpt4 book ai didi

dataframe - "ERROR: ArgumentError: Table returned but a single output column was expected"正在转换中!数据框

转载 作者:行者123 更新时间:2023-12-05 04:19:08 26 4
gpt4 key购买 nike

我想利用 DataFrames.jltransform! 执行简单的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com