# Pandas DataFrame sort_index()函式

Suraj Joshi 2023年1月30日

``````import pandas as pd

pets_df = pd.DataFrame(
{
"Pet": ["Dog", "Cat", "Rabbit", "Fish"],
"Name": ["Rocky", "Luna", "Coco", "Finley"],
"Age(Years)": [3, 5, 5, 4],
},
index=["4", "2", "1", "3"],
)

print(pets_df)
``````

``````      Pet    Name  Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1  Rabbit    Coco           5
3    Fish  Finley           4
``````

## `pandas.DataFrame.sort_index()` 方法

### 語法

``````DataFrame.sort_index(
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
by=None,
)
``````

### 引數

`axis` 沿行(`axis=0`)或列(`axis=1`)排序
`level` 整數或列表。根據指定的索引級別的值進行排序
`ascending` 按升序排序(`ascending=True`)或降序排序(`ascending=False`)
`inplace` 布林型。如果為 `True`，則在原地修改呼叫者的 DataFrame。
`kind` 使用哪種排序演算法。預設值：`quicksort`
`na_position` `NaN` 值放在開頭(`na_position=first`)或結尾(`na_position=last`)。
`sort_remaining` 布林型。如果為 `True`，則在按 `index=multilevel` 的指定級別排序後，也按其他級別排序（按順序）。
`ignore_index` 布林值。如果為 True，則結果軸的標籤將為 0,1，… n-1。
`key` 可呼叫物件。如果不是 `None` 的話，則在排序之前將這個 `key` 函式應用於索引值。

## 示例：使用 `sort_index()` 方法對 Pandas DataFrame 進行索引排序

``````import pandas as pd

pets_df = pd.DataFrame(
{
"Pet": ["Dog", "Cat", "Rabbit", "Fish"],
"Name": ["Rocky", "Luna", "Coco", "Finley"],
"Age(Years)": [3, 5, 5, 4],
},
index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index()

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame Sorted by Index Values:")
print(sorted_df)
``````

``````Initial DataFrame:
Pet    Name Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1 Rabbit    Coco           5
3    Fish Finley           4

DataFrame Sorted by Index Values:
Pet    Name Age(Years)
1 Rabbit    Coco           5
2     Cat    Luna           5
3    Fish Finley           4
4     Dog   Rocky           3
``````

``````import pandas as pd

pets_df = pd.DataFrame(
{
"Pet": ["Dog", "Cat", "Rabbit", "Fish"],
"Name": ["Rocky", "Luna", "Coco", "Finley"],
"Age(Years)": [3, 5, 5, 4],
},
index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index(ascending=False)

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame Sorted in Descending order based Index Values:")
print(sorted_df)
``````

``````Initial DataFrame:
Pet    Name Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1 Rabbit    Coco           5
3    Fish Finley           4

DataFrame Sorted in Descending order based Index Values:
Pet    Name Age(Years)
4     Dog   Rocky           3
3    Fish Finley           4
2     Cat    Luna           5
1 Rabbit    Coco           5
``````

## 示例：使用 `sort_index()` 方法對 Pandas DataFrame 的列進行排序

``````import pandas as pd

pets_df = pd.DataFrame(
{
"Pet": ["Dog", "Cat", "Rabbit", "Fish"],
"Name": ["Rocky", "Luna", "Coco", "Finley"],
"Age(Years)": [3, 5, 5, 4],
},
index=["4", "2", "1", "3"],
)

sorted_df = pets_df.sort_index(axis=1)

print("Initial DataFrame:")
print(pets_df, "\n")

print("DataFrame with sorted Columns:")
print(sorted_df)
``````

``````Initial DataFrame:
Pet    Name  Age(Years)
4     Dog   Rocky           3
2     Cat    Luna           5
1  Rabbit    Coco           5
3    Fish  Finley           4

DataFrame with sorted Columns:
Age(Years)    Name     Pet
4           3   Rocky     Dog
2           5    Luna     Cat
1           5    Coco  Rabbit
3           4  Finley    Fish
``````

Suraj Joshi is a backend software engineer at Matrice.ai.