# 如何按一列的值對 Pandas DataFrame 進行排序

``````import pandas as pd

df = pd.DataFrame(
{
"col1": ["g", "t", "n", "w", "n", "g"],
"col2": [5, 2, 5, 1, 3, 6],
"col3": [0, 7, 2, 8, 1, 2],
}
)
print(df)
``````

``````    col1  col2  col3
0    g     5     0
1    t     2     7
2    n     5     2
3    w     1     8
4    n     3     1
5    g     6     2
``````

``````import pandas as pd

df = pd.DataFrame(
{
"col1": ["g", "t", "n", "w", "n", "g"],
"col2": [5, 2, 5, 1, 3, 6],
"col3": [0, 7, 2, 8, 1, 2],
}
)
print(df.sort_values(by=["col1"]))
``````

``````    col1  col2  col3
0    g     5     0
5    g     6     2
2    n     5     2
4    n     3     1
1    t     2     7
3    w     1     8
``````

``````print(df.sort_values(by=["col1", "col2"]))
``````

``````    col1  col2  col3
0    g     5     0
5    g     6     2
4    n     3     1
2    n     5     2
1    t     2     7
3    w     1     8
``````

## `DataFrame` 排序順序-引數 Ascending

``````print(df.sort_values(by=["col1", "col2"], ascending=False))
``````

``````    col1  col2  col3
3    w     1     8
1    t     2     7
2    n     5     2
4    n     3     1
5    g     6     2
0    g     5     0
``````

## `DataFrame` 排序順序 - 引數 `na_position`

`na_position` 在排序後指定 `NaN` 的位置.`last``NaN` 放在排序的最後，它的預設值是 `first`，將 `NaN` 放在排序結果的開頭。

``````import numpy as np
import pandas as pd

s = pd.Series([np.nan, 2, 4, 10, 7])
print(s.sort_values(na_position="last"))
``````

``````1 2.0
2 4.0
4 7.0
3 10.0
0 NaN
``````