Summary of Python sort (list, dictionary type, Series, DataFrame)

I often use sorting, but there are some differences depending on the type, so I will summarize it. I will summarize each by list, dictionary type, Series, and DataFrame.

I think there are other ways to do it. If you have any recommendations, please let us know.

list

I think the sort method is the easiest. I think that you can respond flexibly if you also know the sorted method. Note that the sorted method does not make any changes to the list itself and returns the sorted list as a return value.

Ascending sort

sort method

lst = [3, 5, 2, 9, 0, 4]
lst.sort()
print(lst)
#=> [0, 2, 3, 4, 5, 9]

sorted function

lst = [3, 5, 2, 9, 0, 4]
lst = sorted(lst)
print(lst)
#=> [0, 2, 3, 4, 5, 9]

Descending sort

sort method

lst_rvs = [3, 5, 2, 9, 0, 4]
lst_rvs.sort()
lst_rvs.reverse()
print(lst_rvs)
#=> [9, 5, 4, 3, 2, 0]

sorted function

lst = [3, 5, 2, 9, 0, 4]
lst = sorted(lst, key=lambda x: -x)
print(lst)
#=> [9, 5, 4, 3, 2, 0]

Dictionary type

key ascending sort

Use the sorted function that was also used in the list. One thing to note about the dictionary type is that the list is returned as a return value.

dct = { 2: 3, 3: 4, 1: 2, 0: 8, 4: 2 }
dct = sorted(dct.items())
print(dct)
#=> [(0, 8), (1, 2), (2, 3), (3, 4), (4, 2)]

I think it's easy to imagine using it as follows.

dct = { 2: 3, 3: 4, 1: 2, 0: 8, 4: 2 }
for k, v in sorted(dct.items()):
    print(str(k) + ": " + str(v))
0: 8
1: 2
2: 3
3: 4
4: 2

Hereafter, the dictionary type will be explained in the output format of the for statement.

key descending sort

dct = {2: 3, 3: 4, 1: 2, 0: 8, 4: 2}
for k, v in sorted(dct.items(), key=lambda x: -x[0]):
    print(str(k) + ": " + str(v))
4: 2
3: 4
2: 3
1: 2
0: 8

value ascending sort

dct = {2: 3, 3: 4, 1: 2, 0: 8, 4: 2}
for k, v in sorted(dct.items(), key=lambda x: x[1]):
    print(str(k) + ": " + str(v))
1: 2
4: 2
2: 3
3: 4
0: 8

value Descending sort

dct = {2: 3, 3: 4, 1: 2, 0: 8, 4: 2}
for k, v in sorted(dct.items(), key=lambda x: -x[1]):
    print(str(k) + ": " + str(v))
0: 8
3: 4
2: 3
1: 2
4: 2

Series (pandas)

index ascending sort

from pandas import Series
ser = Series({2: 3, 3: 4, 1: 2, 0: 8, 4: 2})
ser = ser.sort_index()
print(ser)
0    8
1    2
2    3
3    4
4    2
dtype: int64

index Descending sort

from pandas import Series
ser = Series({2: 3, 3: 4, 1: 2, 0: 8, 4: 2})
ser = ser.sort_index(ascending=False)
print(ser)
4    2
3    4
2    3
1    2
0    8
dtype: int64

value ascending sort

from pandas import Series
ser = Series({2: 3, 3: 4, 1: 2, 0: 8, 4: 2})
ser = ser.sort_values()
print(ser)
1    2
4    2
2    3
3    4
0    8
dtype: int64

value Descending sort

from pandas import Series
ser = Series({2: 3, 3: 4, 1: 2, 0: 8, 4: 2})
ser = ser.sort_values(ascending=False)
print(ser)
0    8
3    4
2    3
4    2
1    2
dtype: int64

DataFrame (pandas)

Sort by label

index ascending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_index()
print(df)
   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                4      3
   HP  Attack  Defence  Special Attack  Special Defence  Speed
1   9       3        1               6                4      3
2   3       4        2               8                2      3
3   3       5        1               9                4      2

index descending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_index(ascending=False)
print(df)

   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                3      3
   HP  Attack  Defence  Special Attack  Special Defence  Speed
3   3       5        1               9                4      2
2   3       4        2               8                2      3
1   9       3        1               6                3      3

column ascending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_index(axis=1)
print(df)
   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                4      3
   Attack  Defence  HP  Special Attack  Special Defence  Speed
2       4        2   3               8                2      3
3       5        1   3               9                4      2
1       3        1   9               6                4      3

column descending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_index(axis=1, ascending=False)
print(df)
   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                3      3
   Speed  Special Defence  Special Attack  HP  Defence  Attack
2      3                2               8   3        2       4
3      2                4               9   3        1       5
1      3                3               6   9        1       3

Sort by value

column value specified ascending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_values(by="Special Defence")
print(df)

   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                3      3
   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
1   9       3        1               6                3      3
3   3       5        1               9                4      2

column value specified descending order

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2,3,1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_values(by="Special Defence", ascending=False)
print(df)
   HP  Attack  Defence  Special Attack  Special Defence  Speed
2   3       4        2               8                2      3
3   3       5        1               9                4      2
1   9       3        1               6                3      3
   HP  Attack  Defence  Special Attack  Special Defence  Speed
3   3       5        1               9                4      2
1   9       3        1               6                3      3
2   3       4        2               8                2      3

index specification

from pandas import DataFrame
df = DataFrame([[3, 4, 2, 8, 2, 3], [3, 5, 1, 9, 4, 2], [9, 3, 1, 6, 3, 3]], index=[2, 3, 1], columns=["HP", "Attack", "Defence", "Special Attack", "Special Defence", "Speed"])
print(df)
df = df.sort_values(by=3, axis=1)
print(df)
ValueError: When sorting by column, axis must be 0 (rows)

I could do it with this, but I can't. .. BUG/ENH: sort_values(by=index_label, axis=1)

I see, I can't do it now. It seems that it will be possible with the next major version upgrade. Scheduled date August 31, 2017 (as of July 15, 2016)

reference

Sort Python dictionary (dict type) by value value Sort HOW TO (document) Python Tips: I want to sort the contents of a dict (dictionary) type pandas.Series.sort_index pandas.Series.sort_values pandas.DataFrame.sort_index pandas.DataFrame.sort_values

Recommended Posts

Summary of Python sort (list, dictionary type, Series, DataFrame)
Summary of Python3 list operations
How to write a list / dictionary type of Python3
Basic grammar of Python3 series (list, tuple)
Summary of built-in methods in Python list
Summary of how to use Python list
Basic operation list of Python3 list, tuple, dictionary, set
How to get dictionary type elements of Python 2.7
Basic operation of Python Pandas Series and Dataframe (1)
List of python modules
Python3 List / dictionary memo
[Memo] Python3 list sort
Summary of Python arguments
[Python] Type Error: Summary of error causes and remedies for'None Type'
Summary of pre-processing practices for Python beginners (Pandas dataframe)
[Python] Summary of table creation method using DataFrame (pandas)
Get the value of a specific key in a list from the dictionary type in the list with Python
Python list, for statement, dictionary
Summary of python file operations
Python --Check type of values
Python data type summary memo
[Python] Copy of multidimensional list
[python] Summary of how to retrieve lists and dictionary elements
Summary of Hash (Dictionary) operation support for Ruby and Python
Python: Create a dictionary from a list of keys and values
[Data science memorandum] Confirmation of the contents of DataFrame type [python]
Learning record (6th day) #Set type #Dictionary type #Mutual conversion of list tuple set #ndarray type #Pandas (DataFrame type)
[Python] Operation memo of pandas DataFrame
Expansion by argument of python dictionary
Python for super beginners Python # dictionary type 1 for super beginners
Division of timedelta in Python 2.7 series
A brief summary of Python collections
Convert list to DataFrame with python
Python Math Series ⓪ Table of Contents
Basic grammar of Python3 system (dictionary)
Python for super beginners Python # dictionary type 2 for super beginners
About the basics list of Python basics
Summary of Python indexes and slices
[OpenCV; Python] Summary of findcontours function
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Python] What is pandas Series and DataFrame?
[Python] Summary of how to use pandas
[Django] Convert QuerySet to dictionary type list
Display a list of alphabets in Python 3
Summary of various for statements in Python
[Python] Summary of array generation (initialization) time! !! !!
[Python] Accelerates loading of time series CSV
[Python2.7] Summary of how to use unittest
[python] Get a list of instance variables
[python] [meta] Is the type of python a type?
[Introduction to Udemy Python3 + Application] 24. Dictionary type
Summary of useful techniques for Python Scrapy
Easy introduction of python3 series and OpenCV3
[Python2.7] Summary of how to use subprocess
Axis option specification summary of Python "numpy.sum (...)"
[Introduction to Udemy Python3 + Application] 16. List type
[Python] Get a list of folders only
To speed up python, summarize the amount of calculation of collection type (list / tuple / dictionary / set) for each purpose.
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
Python Summary
[Python] Create a list of date and time (datetime type) for a certain period