當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas dataframe.sort_index()用法及代碼示例

Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。

Pandas dataframe.sort_index()函數根據給定軸上的標簽對對象進行排序。
本質上,排序算法適用於軸標簽,而不是 DataFrame 中的實際數據,並基於此重新排列數據。我們可以自由選擇要應用的排序算法。我們可以使用“快速排序”,“合並排序”和“堆排序”三種可能的排序算法。

用法:DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True, by=None)

參數:
axis:索引,直接排序的列
level:如果不是,則對指定索引級別的值進行排序
ascending:升序與降序排序
inplace:如果為True,則就地執行操作
kind:{“快速排序”,“合並排序”,“堆排序”},默認為“快速排序”。選擇排序算法。有關更多信息,另請參見ndarray.np.sort。 mergesort是唯一穩定的算法。對於DataFrame,此選項僅在對單個列或標簽進行排序時適用。
na_position:[{'first','last'},默認為'last']首先將NaN放在開頭,最後將NaN放在結尾。未針對MultiIndex實施。
sort_remaining:如果為true且按級別和索引排序是多層,則按指定級別排序後也按其他級別(按順序)排序

返回:sorted_obj:DataFrame

要鏈接到代碼中使用的CSV文件,請單擊此處

範例1:采用sort_index()函數根據索引標簽對 DataFrame 進行排序。

# importing pandas as pd 
import pandas as pd 
  
# Creating the dataframe  
df = pd.read_csv("nba.csv") 
  
# Print the dataframe 
df


正如我們在輸出中看到的那樣,索引標簽已經排序,即(0,1,2,…。)。因此,我們將從其中提取隨機樣本,然後將其排序以進行演示。

讓我們使用以下命令從數據幀中抽取15個元素的隨機樣本dataframe.sample()函數。

# extract the sample dataframe from "df" 
# and store it in "sample_df" 
sample_df = df.sample(15) 
  
# Print the sample data frame 
sample_df

注意:每次我們執行dataframe.sample()函數,它將給出不同的輸出。讓我們使用dataframe.sort_index()函數根據索引標簽對 DataFrame 進行排序

# sort by index labels 
sample_df.sort_index(axis = 0)

輸出:

從輸出中可以看到,索引標簽已排序。

範例2:采用sort_index()函數根據列標簽對 DataFrame 進行排序。

# importing pandas as pd 
import pandas as pd 
  
# Creating the dataframe  
df = pd.read_csv("nba.csv") 
  
# sorting based on column labels 
df.sort_index(axis = 1)

輸出:



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas dataframe.sort_index()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。