Как отсортировать dataframe по столбцу

от admin

pandas.DataFrame.sort_values#

if axis is 0 or ‘index’ then by may contain index levels and/or column labels.

if axis is 1 or ‘columns’ then by may contain column levels and/or index labels.

Axis to be sorted.

ascending bool or list of bool, default True

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

inplace bool, default False

If True, perform operation in-place.

Choice of sorting algorithm. See also numpy.sort() for more information. mergesort and stable are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.

na_position <‘first’, ‘last’>, default ‘last’

Puts NaNs at the beginning if first ; last puts NaNs at the end.

ignore_index bool, default False

If True, the resulting axis will be labeled 0, 1, …, n — 1.

New in version 1.0.0.

Apply the key function to the values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect a Series and return a Series with the same shape as the input. It will be applied to each column in by independently.

Сортировка DataFrame по столбцу в Pandas

Чтобы отсортировать строки DataFrame по столбцу, используйте метод pandas.DataFrame.sort_values() с аргументом by = column_name. Метод sort_values() не изменяет исходный DataFrame, но возвращает отсортированный.

В этом руководстве мы рассмотрим несколько примеров программ, в которых мы будем сортировать DataFrame в порядке возрастания или убывания.

Пример 1: в возрастающем порядке

Порядок сортировки по умолчанию функции sort_values() – возрастающий. В этом примере мы создадим DataFrame и отсортируем строки по определенному столбцу в порядке возрастания.

Вы можете видеть, что строки отсортированы в порядке возрастания.

Пример 2: в порядке убывания

Чтобы отсортировать в порядке убывания, передайте аргумент ascending = False методу sort_values(). В этом примере мы создадим DataFrame и отсортируем строки по определенному столбцу в порядке убывания.

Вы можете видеть, что строки отсортированы в порядке убывания.

Заключение

В этом руководстве по Pandas мы научились сортировать DataFrame в порядке возрастания и убывания, используя sort_values(), с помощью примеров программ Python.

how to sort pandas dataframe from one column

As you can see, months are not in calendar order. So I created a second column to get the month number corresponding to each month (1-12). From there, how can I sort this data frame according to calendar months’ order?

Sachila Ranawaka's user avatar

13 Answers 13

Use sort_values to sort the df by a specific column’s values:

If you want to sort by two columns, pass a list of column labels to sort_values with the column labels ordered according to sort priority. If you use df.sort_values([‘2’, ‘0’]) , the result would be sorted by column 2 then column 0 . Granted, this does not really make sense for this example because each value in df[‘2’] is unique.

drevicko's user avatar

I tried the solutions above and I do not achieve results, so I found a different solution that works for me. The ascending=False is to order the dataframe in descending order, by default it is True . I am using python 3.6.6 and pandas 0.23.4 versions.

You can see more details in pandas documentation here.

vvvvv's user avatar

Joel Carneiro's user avatar

Using column name worked for me.

M Z's user avatar

Niraj's user avatar

Panda’s sort_values does the work.

There are various parameters one can pass, such as ascending (bool or list of bool):

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

As the default is ascending, and OP’s goal is to sort ascending, one doesn’t need to specify that parameter (see the last note below for the way to solve descending), so one can use one of the following ways:

Performing the operation in-place, and keeping the same variable name. This requires one to pass inplace=True as follows:

If doing the operation in-place is not a requirement, one can assign the change (sort) to a variable:

With the same name of the original dataframe, df as

With a different name, such as df_new , as

All this previous operations would give the following output

Finally, one can reset the index with pandas.DataFrame.reset_index , to get the following

A one-liner that sorts ascending, and resets the index would be as follows

Notes:

If one is not doing the operation in-place, forgetting the steps mentioned above may lead one (as this user) to not be able to get the expected result.

There are strong opinions on using inplace . For that, one might want to read this.

One is assuming that the column 2 is not a string. If it is, one will have to convert it:

If one wants in descending order, one needs to pass ascending=False as

How to Sort Data in a Pandas DataFrame

How to Sort Data in a Pandas DataFrame Cover Image

Sorting data is an essential method to better understand your data. In this post, you’ll learn how to sort data in a Pandas DataFrame using the Pandas .sort_values() function, in ascending and descending order, as well as sorting by multiple columns.

Being able to sort your data opens you up to many different opportunities. When working in more visual data tools, like Excel, one of the most common tasks you’re probably familiar with is sorting your data. This allows you to get a sense of the data you’re working with. Being able to do this in Pandas opens you up to a broad type of additional analysis to take on. Let’s get started!

Table of Contents

Video Tutorial

Exploring the Pandas sort_values() Method

We can sort values in a Pandas DataFrame by using the .sort_values() method. The method provides an incredible array of parameters that allow you to customize how your data is sorted to your heart’s content! Let’s take a look at the large variety of options available to us:

The table below breaks down these parameters one by one which allows you to get a sense of how they can change your sorting of data:

Parameter Input Type Default Value Description
by= string or list of strings N/A The name of the column (or row) or list of names to sort by
axis= 0 or 1 0 The axis to be sorted (0 for rows and 1 for columns)
ascending= boolean, or list of booleans True Whether to sort ascendingly or descendingly, and can be different for each column passed in
inplace= boolean False Whether to perform the operation in place or not
kind= string ‘quicksort’ The choice of sorting algorithm, from the following options:
na_position= string ‘last’ Whether to put missing values in first or last position
ignore_index= boolean False Whether to relabel the index axis or not
key= callable None The callable function to apply to help sort the data

The parameters of the Pandas .sort_values() method

There’s a lot to customize in the .sort_values() method. There is also a lot that you can accomplish with just a few parameters. Now let’s dive into sorting your data.

Loading a Sample Pandas DataFrame

Let’s start by loading a sample Pandas DataFrame. The dataset is hosted on Github and can be loaded using the .read_csv() function. We’ll add in an additional parameter to parse our ‘date’ column as dates. After loading the DataFrame, let’s print out the first five rows using the .head() method:

We can see that the DataFrame has four different columns, of three different data types:

  1. ‘date’ is a column describing the date of a sale
  2. ‘gender’ and ‘region’ are string-type columns
  3. ‘sales’ is an integer column that describes the amount of sales made on a given day

Let’s dive into how to sort our Pandas DataFrame using the .sort_values() method.

Sorting a Single Pandas DataFrame Column

The key parameter in the .sort_values() function is the by= parameter, as it tells Pandas which column(s) to sort by. The parameter takes either a single column as a string or a list of columns as a list of strings. Let’s start by sorting our data by a single column. We can sort the data by the ‘sales’ column.

Let’s break down what we did here:

  1. We created a new DataFrame, sorted
  2. We appled the .sort_values() method, passing in only a single column to sort our data by

By default, Pandas will sort data in ascending order. This means that the smallest numbers will be placed at the top. In later sections, you’ll learn how to modify this behavior to sort data in a different order.

Sorting Multiple Pandas DataFrame Columns

The Pandas .sort_values() method makes it easy to sort by multiple columns. In the previous section, you learned to pass in a single column as a string value. If you pass in a list of strings, you can modify the sort behavior. This allows you to establish a sorting hierarchy, where data are first sorted by the values in one column, and then establish a sort order within that order.

Let’s sort our data first by the ‘region’ column and then by the ‘sales’ column.

This looks quite different from the result we achieved in our first example. What’s happened is that our data are first sorted by the ‘region’ column, in ascending order. Values belonging to that region are subsequently sorted by the ‘sales’ column. This means that the ordering is reset when the second outer column is reached.

Change Sort Order in Pandas sort_values

In the examples above, we saw that the sort order defaulted to sort data in ascending order. We can modify this behavior by making use of the ascending= parameter. The parameter accepts a boolean value, meaning either True or False . The default value for this is True . If you wanted to change the data to sort in descending order, simply change the value to False . Let’s give this a try!

We can see above that the data was sorted by the ‘sales’ column but in descending order. This means that the data started with the highest value and goes down from there.

Changing Sort Order for Multiple DataFrame Columns

Similar to how you were able to pass in a list of columns to sort by multiple columns, you’re also able to pass in a list of boolean values to modify the sort order of the various columns. This means that we can sort one column in, say, ascending order and another in descending order. Let’s take a look at this below:

What we did here was pass in a list of boolean values which allowed us to modify the sort order for each column. What we did here was sort first by the ‘region’ column in descending order (meaning reverse alphabetical). We then sorted the data by the ‘sales’ column in increasing order.

Sorting with Missing Values in a Pandas DataFrame

Missing values can often cause unexpected results. Thankfully, Pandas gives you extensive control of how these values are sorted. By default, missing values are sorted at the end of the sort values. Let’s modify our DataFrame to include some missing values:

Using the code above allowed us to insert ten missing values into our DataFrame. We can now explore how the missing values are sorted. Let’s sort our DataFrame by the ‘sales’ column in ascending order and see where our missing data ends up:

We can see that our missing data ended up at the bottom of our resulting DataFrame. This is because the default argument is ‘na_position=’last’ . If we wanted the missing data to appear at the top of the sort order, we can pass in ‘first’ as the argument. Let’s give this a shot:

Resetting an Index with a Sorted Pandas DataFrame

One of the things you may have noticed is that in the previous examples, the resulting DataFrame maintained its original index labels. This may not always be the result you’re hoping for. Because of this, we can modify the ignore_index= argument, which defaults to False . When we modify the boolean to True, we can let Pandas know that we want to effectively reset the index.

The resultant DataFrame’s index begins at 0 and increases through to the length of the DataFrame minus 1. This is a much cleaner DataFrame. However, keep in mind that this modifies the index permanently. If the index represents meaningful labeled data, this may not be the result you were intending.

In the final section of this tutorial, you’ll learn how to sort your Pandas DataFrame in place, meaning that it does not need to be re-assigned.

Sorting a Pandas DataFrame In Place

In all of the above examples, you have learned to re-assign the resulting DataFrame. Pandas, however, also provides you with the option to sort the data in place. What this means is that the original DataFrame is modified directly, without needing to create a new object.

This can be done by modifying the inplace= parameter. This parameter defaults to False ; modifying it to True will allow the operation to occur in place. Let’s see what this looks like:

The resulting DataFrame above has been modified in place, meaning that we didn’t need to re-assign it.

Exercises

It’s time to check test your learning! There are a number of exercises below, for which you can find the solutions by clicking on the toggle. Try to solve them on your own first and then check your understanding by viewing the solution.

Sort your DataFrame first by ‘gender’ and then by ‘region’, both in descending order.

What would happen if you used the following code: df.sort_values(by=[‘region’, ‘gender’], ascending = [True, True, False])

A ValueError would be raised since the two arrays are of different lengths.

Using sorting, how would you get the second-highest sales across all regions?

You could combine .sort_values() with .iloc :

Conclusion and Recap

In this tutorial, you learned how to sort your Pandas DataFrame using the .sort_values() method. As a quick refresher:

  • The Pandas .sort_values() method allows you to sort a dataframe by one or by multiple columns
  • The default sort method is in ascending order placing missing values at the end
  • You can establish different hierarchies by sorting by multiple columns
  • Ignoring your index allows you to build a tidier DataFrame
  • The operation can also be done in place, allowing you to sort without needing to re-assign your values

To learn more about the .sort_values() method, check out the official documentation here.

Читать:
Чем отличается коннектор 5е от 6

Похожие статьи