行の並び替え
準備
1. パッケージのインストール
- R
- Python
- SQL
install.packages("tidyverse")
pip install pandas
なし。
2. パッケージの読み込み
- R
- Python
- SQL
library(tidyverse)
import pandas as pd
なし。
プログラム
1. 列の値を基準に並び替え
- R
- Python
- SQL
構文
df %>%
arrange(col1, col2) # 降順ソートする場合は、dplyr::descを使う
サンプルコード
penguins %>%
arrange(bill_length_mm, desc(body_mass_g))
# # A tibble: 344 × 7
# species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
# <fct> <fct> <dbl> <dbl> <int> <int> <fct>
# 1 Adelie Dream 32.1 15.5 188 3050 female
# 2 Adelie Dream 33.1 16.1 178 2900 female
# 3 Adelie Torgersen 33.5 19 190 3600 female
# 4 Adelie Dream 34 17.1 185 3400 female
# 5 Adelie Torgersen 34.1 18.1 193 3475 NA
# 6 Adelie Torgersen 34.4 18.4 184 3325 female
# 7 Adelie Biscoe 34.5 18.1 187 2900 female
# 8 Adelie Torgersen 34.6 21.1 198 4400 male
# 9 Adelie Torgersen 34.6 17.2 189 3200 female
# 10 Adelie Biscoe 35 17.9 192 3725 female
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows
構文
df.sort_values(by=['col1', 'col2'], ascending=[{ True | False }, { True | False }])
サンプルコード
penguins.sort_values(by=["bill_length_mm", "body_mass_g"], ascending=[True, False])
# species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
# 142 Adelie Dream 32.1 15.5 188 3050 female
# 98 Adelie Dream 33.1 16.1 178 2900 female
# 70 Adelie Torgersen 33.5 19.0 190 3600 female
# 92 Adelie Dream 34.0 17.1 185 3400 female
# 8 Adelie Torgersen 34.1 18.1 193 3475 NaN
# .. ... ... ... ... ... ... ...
# 253 Gentoo Biscoe 55.9 17.0 228 5600 male
# 293 Chinstrap Dream 58.0 17.8 181 3700 female
# 185 Gentoo Biscoe 59.6 17.0 230 6050 male
# 3 Adelie Torgersen NaN NaN NaN NaN NaN
# 271 Gentoo Biscoe NaN NaN NaN NaN NaN
構文
select *
from tbl
order by col1 [{ asc | desc }], col2 [{ asc | desc }]
サンプルコード
select *
from penguins
order by
bill_length_mm asc,
body_mass_g desc;
# | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex |
# | ------- | --------- | -------------- | ------------- | ----------------- | ----------- | ------ |
# | Gentoo | Biscoe | null | null | null | null | null |
# | Adelie | Torgersen | null | null | null | null | null |
# | Adelie | Dream | 32.1 | 15.5 | 188 | 3050 | female |
# | Adelie | Dream | 33.1 | 16.1 | 178 | 2900 | female |
# | Adelie | Torgersen | 33.5 | 19.0 | 190 | 3600 | female |
# | Adelie | Dream | 34.0 | 17.1 | 185 | 3400 | female |
# | Adelie | Torgersen | 34.1 | 18.1 | 193 | 3475 | null |
# | Adelie | Torgersen | 34.4 | 18.4 | 184 | 3325 | female |
# | Adelie | Biscoe | 34.5 | 18.1 | 187 | 2900 | female |
# | Adelie | Torgersen | 34.6 | 21.1 | 198 | 4400 | male |
# | ... | ... | ... | ... | ... | ... | ... |