Python | Индекс Pandas.sort_values ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas Index.sort_values() function is used to sort the index values. The function return a sorted copy of the index. Apart from sorting the numerical values, the function can also sort string type values.

Syntax: Index.sort_values(return_indexer=False, ascending=True)

Parameters :
return_indexer : Should the indices that would sort the index be returned.
ascending : Should the index values be sorted in an ascending order.

Returns : Sorted copy of the index.
sorted_index : pandas.Index

indexer : numpy.ndarray, optional
The indices that the index itself was sorted by.

Example #1: Use Index.sort_values() function to sort the values present in the index.

# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.Index(["Beagle", "Pug", "Labrador",
             "Sephard", "Mastiff", "Husky"])
  
# Print the index
idx

Выход :

Now we will sort the index labels in the ascending order.

# Sorting the index labels
idx.sort_values(ascending = True)

Output :

As we can see in the output, the function has returned an index with its labels sorted.
 
Example #2: Use Index.sort_values() function to sort the index labels in the descending order.

# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.Index([22, 14, 8, 56, 27, 21, 51, 23])
  
# Print the index
idx

Выход :

Now we will sort the index labels in non-increasing order.

# sort the values in descending order
idx.sort_values(ascending = False)

Выход :

Как видно из выходных данных, функция вернула новый индекс с отсортированными в порядке убывания метками.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.