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


Python Pandas Series.rename_axis()用法及代碼示例

Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。

Pandas Series.rename_axis()函數用於設置索引或列的軸名稱。

用法: Series.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)

參數:
mapper:設置軸名稱屬性的值。
index, columns:標量list-like,dict-like或函數轉換可應用於該軸的值。
axis:重命名的軸。
copy:還複製基礎數據。
inplace:直接修改對象,而不創建新的Series或DataFrame。

返回:係列,DataFrame或無

範例1:采用Series.rename_axis()函數重命名給定Series對象的軸。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([10, 25, 3, 11, 24, 6]) 
  
# Create the Index 
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] 
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.rename_axis()函數重命名給定係列對象的軸。

# rename the axis 
result = sr.rename_axis('Beverages') 
  
# Print the result 
print(result)

輸出:


正如我們在輸出中看到的,Series.rename_axis()函數已成功重命名了給定係列對象的軸。

範例2:采用Series.rename_axis()函數重命名給定Series對象的MultiIndex軸。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) 
  
# Create the MultiIndex 
index_ = pd.MultiIndex.from_product([['Names'], ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']], 
                                                                     names =['Level 1', 'Level 2']) 
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.rename_axis()函數重命名給定係列對象的軸。

# rename both the levels of the axis of  
# the given series object 
result = sr.rename_axis(['First_level', 'Second_level']) 
  
# Print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.rename_axis()函數已成功重命名了給定係列對象的軸的兩個級別。



相關用法


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