[Python] Sort the table by sort_values (pandas DataFrame)

[Python] How to sort the table by sort_values (DataFrame of pandas)

How to sort the DataFrame table using the "sort_values method".


[Official page](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html)

There is also a sort_index method, but it is not recommended. FutureWarning: by argument to sort_index is deprecated, please use .sort_values(by=...)


**table of contents**
  1. [Basic Syntax and Main Options](# 1 Basic Syntax and Main Options)
  2. [Table to use](# 2 Table to use)
  3. [Sort by column](# 3 sort by column)
  4. [Ascending sort](# Ascending sort)
  5. [Descending Sort](#Descending Sort)
  6. Sort columns with NaN (sort columns with #nan)
  7. Overwrite
  8. [Sort by line](# 4 sort by line)

## 1. 1. Basic syntax and key options

** ▼ Basic syntax ** df.sort_values(by=['A']) └ "df": Table data └ "by = []": Column / row that is the basis for sorting * Required * └ "A": Column / row name


** ▼ Main options **
option Contents
axis=0 The axis is a column. Default. Optional
axis=1 Make the axis a row.
by=['A'] Axis line/Column name. Mandatory
assending=True Ascending sort. Default. Optional
assending=False Descending sort.
na_position='first' Move NaN to the top.
na_position='last' Move NaN to the bottom. Default. Optional
inplace=False Do not overwrite. Default. Optional
inplace=True Overwrite.

## 2. Table to use Sort by the table with 6 rows and 5 columns below. (NaN is a missing value)

image.png

Creating a table


import pandas as pd
import numpy as np
​
row0 = [0, 0, 'a', 'Ah', 'one']
row1 = [2, 2, 'c', 'U', 'three']
row2 = [4, np.nan,'e', 'O', 'Samurai']
row3 = [1, 1,'b', 'I', 'Two']
row4 = [3, 3,'d', 'e', '肆']
row5 = [5, 5,'e', 'O', 'Samurai']
​
df = pd.DataFrame([row0,row1,row2,row3,row4,row5])
df.columns = ['col0', 'col1', 'col2' ,'col3', 'col4']
df.index = ['row0', 'row1', 'row2', 'row3', 'row4', 'row5']
​
df

Import numpy and use "np.nan" to use the missing value NaN.


## 3. 3. Sort by column ① Ascending sort ② Descending sort ③ Sort of columns including NaN ④ Overwrite
### ① Ascending sort `df.sort_values(by=['A'])`

Enter the column name that will be the sort standard in "A".

The default is "ascending = True" (optional).

Ascending sort


df.sort_values(by=['col0'])

image.png

Sorted in ascending order by the element in column col0.

You can sort alphabets and hiragana in the same way.


### ② Descending sort `df.sort_values(by=['A'], ascending=False)`

Sort in descending order by column name "A".

Descending sort


df.sort_values(by=['col0'], ascending=False)

image.png


### ③ Sort of columns including NaN If the missing value NaN is included in the column that is the basis of the sort, you can set whether to move the NaN to the top or the bottom when sorting.

Na_position ='last' └ Default (optional) └ Move to the bottom

Na_position ='first' └ Move to the top


** ▼ Move NaN to the bottom **

Sort columns containing NaN (default)


df.sort_values(by=['col1'])

image.png


** ▼ Move NaN to the top **

Sort columns containing NaN (top)


df.sort_values(by=['col1'], na_position='first')

image.png


## ④ Overwrite It is possible to set whether to overwrite or not. Do not overwrite the default.

・ ʻInplace = False` └ Default (optional) └ Do not overwrite

・ ʻInplace = True` └ Overwrite


** ▼ Do not overwrite (default) **

Do not overwrite


df.sort_values(by=['col1'])
df

image.png


** ▼ Overwrite **

Overwrite


df.sort_values(by=['col1'], inplace=True)
df

image.png


## 4. Sort by row `sort_values(by=['A'], axis=1)` └ "axis = 1": Sort by line └ "A": Line name

The row direction can only be a representation with numbers or cannot be sorted.


** Table to use ** Sort according to the table "df2" below.

image.png

Table to use


import pandas as pd

col0 = [10, 9, 8, 7]
col1 = [1, 10, 100, 1000]
col2 = [2, 2, 2, 2]
col3 = [0.3, 0.03, 0.003, 0.0003]
col4 = [4, 40, 400, 4000]

df2 = pd.DataFrame(col0, columns=['col0'])
df2['col1'] = col1
df2['col2'] = col2
df2['col3'] = col3
df2['col4'] = col4

df2

** ▼ Ascending sort **

Ascending sort


df2.sort_values(by=[1], axis=1)

image.png


** ▼ Descending sort **

Descending sort


df2.sort_values(by=[1], axis=1, ascending=False)

image.png


Back to top (how to sort a table with #pythonsort_values pandas dataframe )

Recommended Posts

[Python] Sort the table by sort_values (pandas DataFrame)
Sort by pandas
Pandas of the beginner, by the beginner, for the beginner [Python]
[python] Create table from pandas DataFrame to postgres
Python application: Pandas # 3: Dataframe
[Python] Summary of table creation method using DataFrame (pandas)
Sort by date in python
The Power of Pandas: Python
[Python] Open the csv file in the folder specified by pandas
Python hand play (Pandas / DataFrame beginning)
[Python] Operation memo of pandas DataFrame
[Python] Sort iterable by multiple conditions
python / pandas / dataframe / How to get the simplest row / column / index / column
[Python] How to add rows and columns to a table (pandas DataFrame)
Create a pandas Dataflame by searching the DB table using sqlalchemy
Sort the file names obtained by Python glob in numerical order
[Python] What is pandas Series and DataFrame?
Update Pandas DataFrame elements by column name
[Python] Sort
Associate the table set in python models.py
Python application: Pandas Part 4: DataFrame concatenation / combination
Read the file line by line in Python
[Pandas] Expand the character string to DataFrame
Read the file line by line in Python
Python # sort
[Reinventing the wheel] Human-powered tournament sort [Python]
[Python] Add total rows to Pandas DataFrame
How to sort by specifying a column in the Python Numpy array.
Is there NaN in the pandas DataFrame?
[python] How to sort by the Nth Mth element of a multidimensional array
Comparison of Python (+ Pandas), R, Julia (+ DataFrames) (summary of table contents, access by column)
The first web app created by Python beginners
[Python pandas] Create an empty DataFrame from an existing DataFrame
Sort the elements of the array by specifying the conditions
Python pandas: Search for DataFrame using regular expressions
[Automation] Extract the table in PDF with Python
How to erase the characters output by Python
I tried using the Datetime module by Python
[Python] How to sort instances by instance variables
Basic operation of Python Pandas Series and Dataframe (1)
Python> Sort by number and sort by alphabet> Use sorted ()
Sort tuple list in Python by specifying the ascending / descending order of multiple keys
My pandas (python)
python pandas notes
Find the cumulative distribution function by sorting (Python version)
Extract the table of image files with OneDrive & Python
Image processing by matrix Basics & Table of Contents-Reinventor of Python image processing-
Sort in Python. Next, let's think about the algorithm.
Check if the expected column exists in Pandas DataFrame
[Python] Specify the range from the image by dragging the mouse
Python3 datetime is faster just by specifying the timezone
Summary of pre-processing practices for Python beginners (Pandas dataframe)
Read the xml file by referring to the Python tutorial
Shift the alphabet string by N characters in Python
The VIF calculated by Python and the VIF calculated by Excel are different .. ??
Store the stock price scraped by Python in the DB
How to save a table scraped by python to csv
[Python] How to rewrite the table style with python-pptx [python-pptx]
[Python] Sort spreadsheet worksheets by sheet name with gspread
Report environment construction by python (matplotlib, pandas, sphinx) + wkhtmltopdf
Create a dictionary by searching the table using sqlalchemy