Julia中的DataFrame类型允许您以数组形式访问它,因此可以通过索引删除列:
df = df[:,[1:2,4:end]] # remove column 3
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是我经常只知道列的名称,而不知道表中的列索引.
有没有按名称删除列的内置方法?
或者,有没有比这更好的方法呢?
colind = findfirst(names(df), colsymbol)
df = df[:,[1:colind-1,colind+1:end]]
Run Code Online (Sandbox Code Playgroud)
以上是容易出错的; 有一些边缘情况(单列,第一列,最后一列,符号不在表中等)
谢谢
DSM*_*DSM 25
你可以使用delete!:
julia> df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"], C = 2:5)
4x3 DataFrame
|-------|---|-----|---|
| Row # | A | B | C |
| 1 | 1 | "M" | 2 |
| 2 | 2 | "F" | 3 |
| 3 | 3 | "F" | 4 |
| 4 | 4 | "M" | 5 |
julia> delete!(df, :B)
4x2 DataFrame
|-------|---|---|
| Row # | A | C |
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 3 | 4 |
| 4 | 4 | 5 |
Run Code Online (Sandbox Code Playgroud)
对于更一般的操作,请记住您也可以传递一系列符号或bool数组,因此任意复杂的选择如
julia> df[~[(x in [:B, :C]) for x in names(df)]]
4x1 DataFrame
|-------|---|
| Row # | A |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
julia> df[setdiff(names(df), [:C])]
4x1 DataFrame
|-------|---|
| Row # | A |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
Run Code Online (Sandbox Code Playgroud)
也会工作.
由于delete!引发弃用警告,建议使用select!:
julia> d = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
? Row ? a ? b ?
? ? Int64 ? Int64 ?
???????????????????????
? 1 ? 1 ? 4 ?
? 2 ? 2 ? 5 ?
? 3 ? 3 ? 6 ?
julia> select!(d, Not(:a))
3×1 DataFrame
? Row ? b ?
? ? Int64 ?
???????????????
? 1 ? 4 ?
? 2 ? 5 ?
? 3 ? 6 ?
Run Code Online (Sandbox Code Playgroud)
从 Julia 1.0 开始,您将需要使用deletecols!:
https://juliadata.github.io/DataFrames.jl/stable/lib/functions.html#DataFrames.deletecols!
\n\njulia> d = DataFrame(a=1:3, b=4:6)\n3\xc3\x972 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 a \xe2\x94\x82 b \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x82 Int64 \xe2\x94\x82 Int64 \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1 \xe2\x94\x82 1 \xe2\x94\x82 4 \xe2\x94\x82\n\xe2\x94\x82 2 \xe2\x94\x82 2 \xe2\x94\x82 5 \xe2\x94\x82\n\xe2\x94\x82 3 \xe2\x94\x82 3 \xe2\x94\x82 6 \xe2\x94\x82\n\njulia> deletecols!(d, 1)\n3\xc3\x971 DataFrame\n\xe2\x94\x82 Row \xe2\x94\x82 b \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x82 Int64 \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1 \xe2\x94\x82 4 \xe2\x94\x82\n\xe2\x94\x82 2 \xe2\x94\x82 5 \xe2\x94\x82\n\xe2\x94\x82 3 \xe2\x94\x82 6 \xe2\x94\x82\nRun Code Online (Sandbox Code Playgroud)\n