📜  Python|熊猫系列.sort_index()

📅  最后修改于: 2022-05-13 01:55:41.125000             🧑  作者: Mango

Python|熊猫系列.sort_index()

Pandas 系列是带有轴标签的一维 ndarray。标签不必是唯一的,但必须是可散列的类型。该对象支持基于整数和基于标签的索引,并提供了许多用于执行涉及索引的操作的方法。

Pandas Series.sort_index()函数用于对给定系列对象的索引标签进行排序。

示例 #1:使用Series.sort_index()函数对给定系列对象的索引标签进行排序。

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

输出 :

现在我们将使用Series.sort_index()函数对给定系列对象的索引标签进行排序。

# sort the index labels
sr.sort_index()

输出 :

正如我们在输出中看到的, Series.sort_index()函数已成功对给定系列对象的索引标签进行排序。示例 #2:使用Series.sort_index()函数对给定系列对象的索引标签进行排序。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
  
# Create the Index
index_ = [5, 3, 2, 1, 4]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.sort_index()函数对给定系列对象的索引标签进行排序。

# sort the index labels
sr.sort_index()

输出 :

正如我们在输出中看到的, Series.sort_index()函数已成功对给定系列对象的索引标签进行排序。