上节讨论了 按行选取的 filter, 而本节将讨论 按列选取的 select。 然而, select 不止能用于按列选取,本节还会讨论更加广泛的用法。 首先,创建具有多列的数据集:
function responses()
id = [1, 2]
q1 = [28, 61]
q2 = [:us, :fr]
q3 = ["F", "B"]
q4 = ["B", "C"]
q5 = ["A", "E"]
DataFrame(; id, q1, q2, q3, q4, q5)
end
responses()
| id | q1 | q2 | q3 | q4 | q5 |
|---|---|---|---|---|---|
| 1 | 28 | us | F | B | A |
| 2 | 61 | fr | B | C | E |
上述数据表示某问卷中五个问题的(q1,q2,…,q5)的答案。 首先,选取数据集中的一些列。 照例使用 Symbol 指定列:
select(responses(), :id, :q1)
| id | q1 |
|---|---|
| 1 | 28 |
| 2 | 61 |
也可以使用字符串:
select(responses(), "id", "q1", "q2")
| id | q1 | q2 |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
如果要选取除了 某些列外的所有列,请使用 Not:
select(responses(), Not(:q5))
| id | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| 1 | 28 | us | F | B |
| 2 | 61 | fr | B | C |
Not 也适用于多列:
select(responses(), Not([:q4, :q5]))
| id | q1 | q2 | q3 |
|---|---|---|---|
| 1 | 28 | us | F |
| 2 | 61 | fr | B |
当然也可以将要保留的列参数和 不 保留的列参数组合起来:
select(responses(), :q5, Not(:id))
| q5 | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| A | 28 | us | F | B |
| E | 61 | fr | B | C |
注意,q5 是 select 返回的 DataFrame 的第一列。 要实现如上的操作,更聪明的做法是使用 :。 冒号 : 可以认为是 前述条件尚未包含的所有列。 例如:
select(responses(), :q5, :)
| q5 | id | q1 | q2 | q3 | q4 |
|---|---|---|---|---|---|
| A | 1 | 28 | us | F | B |
| E | 2 | 61 | fr | B | C |
或者,把 q5 放在第二个位置16:
select(responses(), 1, :q5, :)
| id | q5 | q1 | q2 | q3 | q4 |
|---|---|---|---|---|---|
| 1 | A | 28 | us | F | B |
| 2 | E | 61 | fr | B | C |
NOTE: 正如你所看到的那样,有多种列选择方法。 它们都被称为 列选择器。
可以使用:
Symbol:select(df, :col)
String:select(df, "col")
Integer:select(df, 1)
甚至可以使用 select 重命名列,语法是 source => target:
select(responses(), 1 => "participant", :q1 => "age", :q2 => "nationality")
| participant | age | nationality |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
另外,还可以使用 “splat” 算符 ... (请查阅 Section 3.3.11) 写作如下形式:
renames = (1 => "participant", :q1 => "age", :q2 => "nationality")
select(responses(), renames...)
| participant | age | nationality |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
16. 感谢 Sudete 在 Discourse 论坛 (https://discourse.julialang.org/t/pull-dataframes-columns-to-the-front/60327/4) 上给予的建议。↩︎