Python Pandas——返回已排序的索引副本


要在Pandas中返回已排序的索引副本,請使用**index.sort_values()**方法。首先,匯入所需的庫 -

import pandas as pd

建立Pandas索引 -

index = pd.Index([50, 10, 70, 95, 110, 90, 30])

顯示Pandas索引 -

print("Pandas Index...\n",index)

對索引值進行排序。預設情況下,按升序排序 -

print("\nSort the index values...\n",index.sort_values())

例子

以下為程式碼 -

import pandas as pd

# Creating Pandas index
index = pd.Index([50, 10, 70, 95, 110, 90, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Sort index values
# By default, sorts in Ascending order
print("\nSort the index values...\n",index.sort_values())

輸出

這將產生以下輸出 -

Pandas Index...
Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')

Number of elements in the index...
7

The dtype object...
int64

Sort the index values...
Int64Index([10, 30, 50, 70, 90, 95, 110], dtype='int64')

更新於: 14-Oct-2021

138 瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告