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


Python Pandas MultiIndex.sortlevel()用法及代碼示例

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

Pandas MultiIndex.sortlevel()函數在請求的級別對MultiIndex進行排序。結果將遵守該級別上關聯因子的原始排序。

用法: MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True)

參數:
level:[list-like,int或str,默認值0]如果給出了字符串,則必須是級別的名稱如果list-like必須是級別的名稱或整數
ascending:False降序排序也可以是指定有向順序的列表
sort_remaining:按級別後的剩餘級別排序。

返回:
sorted_index:結果索引
indexer:原始索引中輸出值的索引

範例1:采用MultiIndex.sortlevel()函數以降序對MultiIndex的第0級進行排序。

# importing pandas as pd 
import pandas as pd 
  
# Create the MultiIndex 
midx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',  
                                     'Anthropology', 'Science'], 
                                             [88, 84, 98, 95]]) 
  
# Print the MultiIndex 
print(midx)

輸出:

現在,讓我們按降序對MultiIndex的第0級進行排序。

# sort the 0th level in descending order. 
midx.sortlevel(level = 0, ascending = False)

輸出:

從輸出中可以看到,該函數返回了一個新對象,該對象的第0級按降序排列。

範例2:采用MultiIndex.sortlevel()函數以升序對MultiIndex的第一級進行排序。

# importing pandas as pd 
import pandas as pd 
  
# Create the MultiIndex 
midx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',  
                                     'Anthropology', 'Science'],  
                                             [88, 84, 98, 95]]) 
  
# Print the MultiIndex 
print(midx)

輸出:

現在,讓我們按升序對MultiIndex的第一級進行排序。

# sort the 1st level of the MultiIndex in increasing order. 
midx.sortlevel(level = 1, ascending = True)

輸出:

從輸出中可以看到,該函數返回了一個新對象,該對象的第一級按升序排序。



相關用法


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