Julia DataFrame:按名称删除列

39

在Julia中,DataFrame类型允许您将其视为数组进行访问,因此可以通过索引方式删除列:

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

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

是否有一种内置的方法可以按名称删除列?

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

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

上述方法容易出现故障;存在一些极端情况(单列、第一列、最后一列、符号不在表格中等)。

谢谢


使用 columnindex(df, :your_column_symbol) 访问列索引。 - Merlin
3个回答

52
你可以使用select!:
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> select!(df, Not(:B))
4x2 DataFrame
|-------|---|---|
| Row # | A | C |
| 1     | 1 | 2 |
| 2     | 2 | 3 |
| 3     | 3 | 4 |
| 4     | 4 | 5 |

关于更一般的操作,请记住您也可以传递符号数组或布尔数组,因此像这样任意复杂的选择:

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
只是提一下,这个例子在 Julia 0.21.0 / DataFrames 1.3.1 上不起作用。@LyxUser12345 的答案使用 select! 确实有效。 - quantif
2
请修改答案,因为它已经过时了。 - xiaodai

14

由于delete!会产生废弃警告,建议使用 select!

julia> d = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64Int64 │
├─────┼───────┼───────┤
│ 114     │
│ 225     │
│ 336     │

julia> select!(d, Not(:a))
3×1 DataFrame
│ Row │ b     │
│     │ Int64 │
├─────┼───────┤
│ 14     │
│ 25     │
│ 36

deletecols!同样会抛出警告。 - Mike

4

从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     │
│     │ Int64Int64 │
├─────┼───────┼───────┤
│ 114     │
│ 225     │
│ 336     │

julia> deletecols!(d, 1)
3×1 DataFrame
│ Row │ b     │
│     │ Int64 │
├─────┼───────┤
│ 14     │
│ 25     │
│ 36

4
deletecols!在Julia 1.3.1中已被弃用,@LyxUser12345的答案使用select!是可行的。 - quantif
4
对我来说,“删除”操作的“删除”按键名称似乎比“选择(非)”更直接。:-/ - Antonello

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接