<jupyter_start><jupyter_text>DataFrames.jl 介紹 (三): Reshaping / Sorting![](https://juliadata.github.io/DataFrames.jl/stable/assets/logo.png)DataFrames.jl 官方網站: [https://juliadata.github.io/DataFrames.jl/stable/](https://juliadata.github.io/DataFrames.jl/stable/)DataFrames.jl GitHub: [https://github.com/JuliaData/DataFrames.jl/blob/master/docs/src/index.md](https://github.com/JuliaData/DataFrames.jl/blob/master/docs/src/index.md)  0. 安裝如果尚未安裝過 DataFrames.jl 的話, 執行 `Pkg.add()` 進行安裝<jupyter_code>using Pkg
Pkg.add(PackageSpec(name="DataFrames", version="0.20.2"))<jupyter_output>[32m[1m  Updating[22m[39m registry at `C:\Users\james\.julia\registries\General`
[32m[1m  Updating[22m[39m git-repo `https://github.com/JuliaRegistries/General.git`
[2K[36m[1mFetching:[22m[39m [========================================>]  100.0 %.0 %[?25h[32m[1m Resolving[22m[39m package versions...
[32m[1m  Updating[22m[39m `C:\Users\james\.julia\environments\v1.2\Project.toml`
[90m [no changes][39m
[32m[1m  Updating[22m[39m `C:\Users\james\.julia\environments\v1.2\Manifest.toml`
[90m [no changes][39m<jupyter_text>1. Reshaping<jupyter_code>using DataFrames, CSV
df = CSV.read("iris.csv", delim=",")
first(df, 5)<jupyter_output><empty_output><jupyter_text>stack `stack()` 函式可將 DataFrame 的形狀改變成"長"形，也就是將各 column 展開轉為 row 及其對應值，並自動產生兩個新的 column 名為 `variable` 和 `value`。呼叫 `stack()` 指定要展開的 column 時，可以使用 index 值也可以使用 column 名稱。以下範例為使用 index 值，原先 DataFrame 的形狀為 (150, 5)，轉換後變成 (750, 2)。<jupyter_code>longdf = stack(df, 1:5)
size(longdf)
first(longdf, 5)
last(longdf, 5)<jupyter_output><empty_output><jupyter_text>以下範例為使用 column 名稱。<jupyter_code>longdf = stack(df, [:SepalLength, :SepalWidth, :PetalLength, :PetalWidth])
size(longdf)
first(longdf, 5)
last(longdf, 5)<jupyter_output><empty_output><jupyter_text>下列範例示範僅 stack 2 個欄位與指定其 ID 值 (Class 欄位)。<jupyter_code>longdf = stack(df, [:SepalLength, :SepalWidth], :Class)
first(longdf, 5)
last(longdf, 5)<jupyter_output><empty_output><jupyter_text>unstack`unstack()` 的功能與 `stack()` 相反, 可將長形的 DataFrame 轉變為原先"寬"形的.<jupyter_code># 為能正確執行 unstack, 需先在 DataFrame 中加入 index 欄位.
df.id = 1:size(df, 1)
longdf = stack(df, Not([:Class, :id]))<jupyter_output><empty_output><jupyter_text>進行 unstack, 將長資料集轉換還原成原先的 shape.<jupyter_code>widedf = unstack(longdf, :variable, :value)
size(widedf)
first(widedf, 5)
last(widedf, 5)<jupyter_output><empty_output><jupyter_text>2. Sorting排序的函式有 `sort()` 及 `sort!()`, 差異點在於 `sort!()` 會排序並更新原 DataFrame, 而 `sort()` 不會更新原 DataFrame.<jupyter_code>df = CSV.read("iris.csv", delim=",") |> DataFrame
first(df, 5)<jupyter_output><empty_output><jupyter_text>預設的排序是對每個 column 的值依序進行由小到大 (ascending) 的排序<jupyter_code>sort(df)<jupyter_output><empty_output><jupyter_text>使用 `rev=true` 參數值, 進行由大到小 (descending) 排序.<jupyter_code>sort(df, rev = true)<jupyter_output><empty_output><jupyter_text>指定欲排序的欄位, 可以用 index 也可以用欄位名.<jupyter_code>sort(df, [1, 2, 3, 4], rev=true)
# 結果上例完全相同<jupyter_output><empty_output><jupyter_text>若要針對 2 個欄位進行排序, 而且排序方法不同的話, 可依照下面示範.<jupyter_code># 一個欄位是 descending 排序, 一個是 ascending
sort(df, (:Class, :PetalWidth), rev=(true,false))
# 使用 order, 結果與上例完全相同
sort(df, (order(:Class, rev=true), order(:PetalWidth, rev=false)))<jupyter_output><empty_output><jupyter_text>下面範例是使用 `by` 參數根據欄位值長度 (Class名稱長度) 排序.<jupyter_code>sort(df, :Class, by=length)
first(df, 5)
last(df, 5)<jupyter_output><empty_output><jupyter_text>unique使用 `Base.unique()` 函式，可以查看欄位中不重覆資料。<jupyter_code>unique(df[!, :Class])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18572241183162685, 'fraction_numerical': 0.028156996587030716, 'mean_word_length': 9.01994301994302, 'pattern_counts': {'":': 0, '<': 56, '<?xml version=': 0, '>': 58, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '327465', 'license': 'Apache-2.0', 'n_tokens_mistral': 1861, 'n_tokens_neox': 1807, 'n_words': 214, 'path': 'example/julia_019_example.ipynb', 'repo_name': 'h164654156465/1st-JuliaMarathon', 'size': '3516'}