pandas - 排序
Series 排序
- 语法结构:
Series.sort_values(ascending=True, inplace=False)
参数说明:
ascending:默认为True升序排序,为False降序排序;
inplace:是否修改原始Series;
DataFrame 排序
- 语法结构:
DataFrame.sort_values(by, ascending=True, inplace=False)
参数说明:
by:字符串或者List<字符串>,单列排序或者多列排序;
ascending:bool或者List,升序还是降序,如果是list对应by的多列,默认升序,为False时降序;
inplace:是否修改原始DataFrame,为True时修改源数据;
实例
- 读取文件:以 match.csv 为例
import pandas as pd df = pd.read_csv("match.csv") df
- Series 排序
import pandas as pd df = pd.read_csv("match.csv") # 按照 Number 升序排序 df["Number"].sort_values() 输出: 0 0.0 291 0.0 22 0.0 393 0.0 141 0.0 ... 372 90.0 5 90.0 68 92.0 1 99.0 457 NaN Name: Number, Length: 458, dtype: float64 # 按照 Number 降序排序 df["Number"].sort_values(ascending=False) 输出: 1 99.0 68 92.0 5 90.0 372 90.0 398 88.0 ... 347 0.0 188 0.0 205 0.0 0 0.0 457 NaN Name: Number, Length: 458, dtype: float64 # 也可以将文本排序 df["Name"].sort_values() 输出: 152 Aaron Brooks 356 Aaron Gordon 328 Aaron Harrison 404 Adreian Payne 312 Al Horford ... 270 Xavier Munford 402 Zach LaVine 271 Zach Randolph 237 Zaza Pachulia 457 NaN Name: Name, Length: 458, dtype: object
- DataFrame 排序
- 单列排序
import pandas as pd df =pd.read_csv('match.csv') #按照 Number 降序排序 df.sort_values(by = "Number",ascending = False) # 默认升序排序,ascending=True时,升序排序 #输出如下:
- 多列排序-1——同升同降
import pandas as pd df =pd.read_csv('match.csv') #按照 Age 与 Number 均升序排序,不修改源数据 df.sort_values(by = ["Age","Number"],ascending=True,inplace=False) #输出如下:
- 多列排序-2——指定升降序
import pandas as pd df =pd.read_csv('match.csv') # 按照 Age 与 Number 排序,分别指定升序和降序 df.sort_values(by = ["Age","Number"],ascending = [True,False]) # ascending可以接受str类型,所以True与False没有加引号 #输出如下: