DataFrame.sort_values
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, ignore_index=False, key=None)
按任一轴上的值进行排序。
Parameters
by | 要排序的名称或名称列表。 |
---|---|
axis | 0 or index:作用于行;1 or columns:作用于列 |
ascending | 升序与降序排序 |
inplace | False:返回一个副本;True:就地执行操作并返回None |
kind | 排序算法的选择:quicksort、mergesort、heapsort、stable |
na_position | first:将NaN值放在开头;last:将NaN值放在末尾 |
ignore_index | True:轴将被标记为0,1,…,n-1 |
key | 在排序之前将键函数应用于值。类似于内置sorted()函数中的key |
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
df.sort_values(by=['age'])
------------------------------------------
site age price color
first google 18 1.0 red
third wiki 22 3.0 None
second baidu 39 2.0 black
forth pandas 45 4.0 red
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
df.sort_values(by=['age'], ascending=False)
------------------------------------------------
site age price color
forth pandas 45 4.0 red
second baidu 39 2.0 black
third wiki 22 3.0 None
first google 18 1.0 red