4.4 Select
上节讨论了 按行选取的 filter, 而本节将讨论 按列选取的 select。 然而, select 不止能用于按列选取,本节还会讨论更加广泛的用法。 首先,创建具有多列的数据集:
1. function responses()
2. id = [1, 2]
3. q1 = [28, 61]
4. q2 = [:us, :fr]
5. q3 = ["F", "B"]
6. q4 = ["B", "C"]
7. q5 = ["A", "E"]
8. DataFrame(; id, q1, q2, q3, q4, q5)
9. end
10. responses()
Table 7: Responses.
| id | q1 | q2 | q3 | q4 | q5 |
|---|---|---|---|---|---|
| 1 | 28 | us | F | B | A |
| 2 | 61 | fr | B | C | E |
上述数据表示某问卷中五个问题的(q1,q2,…,q5)的答案。 首先,选取数据集中的一些列。 照例使用 Symbol 指定列:
1. select(responses(), :id, :q1)
| id | q1 |
|---|---|
| 1 | 28 |
| 2 | 61 |
也可以使用字符串:
1. select(responses(), "id", "q1", "q2")
| id | q1 | q2 |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
如果要选取除了 某些列外的所有列,请使用 Not:
1. select(responses(), Not(:q5))
| id | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| 1 | 28 | us | F | B |
| 2 | 61 | fr | B | C |
Not 也适用于多列:
1. select(responses(), Not([:q4, :q5]))
| id | q1 | q2 | q3 |
|---|---|---|---|
| 1 | 28 | us | F |
| 2 | 61 | fr | B |
当然也可以将要保留的列参数和 不 保留的列参数组合起来:
1. select(responses(), :q5, Not(:id))
| q5 | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| A | 28 | us | F | B |
| E | 61 | fr | B | C |
注意,q5 是 select 返回的 DataFrame 的第一列。 要实现如上的操作,更聪明的做法是使用 :。 冒号 : 可以认为是 前述条件尚未包含的所有列。 例如:
1. select(responses(), :q5, :)
| q5 | id | q1 | q2 | q3 | q4 |
|---|---|---|---|---|---|
| A | 1 | 28 | us | F | B |
| E | 2 | 61 | fr | B | C |
或者,把 q5 放在第二个位置16:
1. 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:
1. select(responses(), 1 => "participant", :q1 => "age", :q2 => "nationality")
| participant | age | nationality |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
另外,还可以使用 “splat” 算符 ... (请查阅 Section 3.3.11) 写作如下形式:
1. renames = (1 => "participant", :q1 => "age", :q2 => "nationality")
2. select(responses(), renames...)
| participant | age | nationality |
|---|---|---|
| 1 | 28 | us |
| 2 | 61 | fr |
CC BY-NC-SA 4.0 Jose Storopoli, Rik Huijzer, Lazaro Alonso, 刘贵欣 (中文翻译), 田俊 (中文审校)
