Python | Панды Series.sort_values ()

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

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.sort_values() function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm.

Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)

Parameter :
axis : Axis to direct sorting.
ascending : If True, sort values in ascending order, otherwise descending.
inplace : If True, perform operation in-place.
kind : Choice of sorting algorithm.
na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.

Returns : Series

Example #1: Use Series.sort_values() function to sort the elements of the given series object in lexicographical order.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio", "Moscow"])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ="2014-08-01 10:00", freq ="W"
                     periods = 6, tz = "Europe/Berlin"
  
# set the index
sr.index = didx
  
# Print the series
print(sr)

Выход :

Now we will use Series.sort_values() function to sort the elements of the given series object in ascending order.

# sort the values in ascending order
sr.sort_values()

Выход :

As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in ascending order.
 
Example #2: Use Series.sort_values() function to sort the elements of the given series object in descending order.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
  
# Print the series
print(sr)

Выход :

Now we will use Series.sort_values() function to sort the elements of the given series object in descending order.

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

Выход :

As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in descending order.

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

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