知道为什么这不起作用吗?
transform(df, All() .=> string; renamecols=false)
不是应该将
string
函数应用于所有列并因此转换它们吗?添加 ByRow
时它可以工作,但是这样的操作应该在整个列上而不是在每一行上。
您所描述的内容符合预期。
string
获取整个向量并将其转换为字符串(向量,而不是其内容)。要处理向量的元素,请使用 ByRow
,正如您所评论的,或使用广播:
julia> df = DataFrame(x=1:2, y=3:4, z=5:6)
2×3 DataFrame
Row │ x y z
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 3 5
2 │ 2 4 6
julia> transform(df, All() .=> string; renamecols=false)
2×3 DataFrame
Row │ x y z
│ String String String
─────┼────────────────────────
1 │ [1, 2] [3, 4] [5, 6]
2 │ [1, 2] [3, 4] [5, 6]
julia> transform(df, All() .=> ByRow(string); renamecols=false)
2×3 DataFrame
Row │ x y z
│ String String String
─────┼────────────────────────
1 │ 1 3 5
2 │ 2 4 6
julia> string.(df) # broadcasting version
2×3 DataFrame
Row │ x y z
│ String String String
─────┼────────────────────────
1 │ 1 3 5
2 │ 2 4 6
在
All() .=> string
中仍然得到向量的原因是 transform
强制结果中的行数不变。因此生成的字符串被重用。请注意,使用 combine
您将得到一行:
julia> combine(df, All() .=> string; renamecols=false)
1×3 DataFrame
Row │ x y z
│ String String String
─────┼────────────────────────
1 │ [1, 2] [3, 4] [5, 6]
要突出显示该问题,请参阅
string
如何在没有 DataFrames.jl 的情况下对向量进行操作:
julia> string([1, 2])
"[1, 2]"