Сортировать фрейм данных Pandas по двум или более столбцам
In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values()method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function.
First, Let’s Create a Dataframe:
Python3
#import python libraryimport pandas as pd # dictionarydata_frame = { "name": ["Akash Kumar", "Diksha Tewari", "Bhawna Gourh", "Ayush Sharma"], "age": [20, 21, 22, 23], "favorite_color": ["black", "Yellow", "Pink", "Orange"], "grade": [88, 92, 95, 70]} # create data frame with indexingdf = pd.DataFrame(data_frame, index = [1, 2, 3, 4]) # printing the dataframedf |
Выход:

Пример 1. Сортировка фрейма данных по столбцу «возраст» (в порядке убывания) и «оценка» (в порядке возрастания).
Python3
# sort the dataframe# based on age and gradedf.sort_values(["age", "grade"], ascending = [False, True]) |
Выход:

Example 2: Sort Dataframe based on ‘name’ and ‘favorite_color’ column in ascending order.
Python3
# sort the dataframe based # on name and favorite_colrdf.sort_values(["name", "favorite_color"], ascending=[True, True]) |
Выход:

Example 3: In-place sorting of Dataframe based on ‘grade’ and ‘favorite_color’ column. In case of in-place sorting, Dataframe.sort_values() method returns nothing it performs changes in the actual dataframe.
Python3
df.sort_values(["grade", "favorite_color"], axis = 0, ascending = True, inplace = True, na_position ="first") # printing the dataframedf |
Выход:

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