Julia DataFrame:按名称删除列

时间:2014-07-09 23:48:35

标签: dataframe julia

Julia中的DataFrame类型允许您以数组形式访问它,因此可以通过索引删除列:

df = df[:,[1:2,4:end]] # remove column 3

这种方法的问题在于我经常只知道列的名称,而不知道表中的列索引。

是否有按名称删除列的内置方法?

或者,有没有比这更好的方法呢?

colind = findfirst(names(df), colsymbol)
df = df[:,[1:colind-1,colind+1:end]]

以上是容易出错的;有一些边缘情况(单列,第一列,最后一列,符号不在表中等)

谢谢

3 个答案:

答案 0 :(得分:21)

您可以使用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 |

对于更一般的操作,请记住您也可以传递一系列符号或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 |

也可以。

答案 1 :(得分:2)

从Julia 1.0开始,您将要使用deletecols!

https://juliadata.github.io/DataFrames.jl/stable/lib/functions.html#DataFrames.deletecols

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> deletecols!(d, 1)
3×1 DataFrame
│ Row │ b     │
│     │ Int64 │
├─────┼───────┤
│ 1   │ 4     │
│ 2   │ 5     │
│ 3   │ 6     │

答案 2 :(得分:0)

由于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     │
相关问题