Pandas:按索引和列对 dataframe 进行排序
您可以使用以下语法按索引和列对 pandas DataFrame 进行排序:
df = df. sort_values (by = [' column_name ', ' index '], ascending = [ False , True ])
以下示例展示了如何在实践中使用此语法。
示例:按索引和列对 DataFrame 进行排序
以下代码显示了如何按名为点的列然后按索引列对 pandas DataFrame 进行排序:
import pandas as pd #createDataFrame df = pd. DataFrame ({' id ': [1, 2, 3, 4, 5, 6, 7, 8], ' points ': [25, 15, 15, 14, 20, 20, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}). set_index (' id ') #view first few rows df. head () points assists rebounds id 1 25 5 11 2 15 7 8 3 15 7 10 4 14 9 6 5 20 12 6 #sort by points and then by index df. sort_values (by = [' points ', ' id '], ascending = [ False , True ]) points assists rebounds id 8 29 4 12 1 25 5 11 7 25 9 9 5 20 12 6 6 20 9 5 2 15 7 8 3 15 7 10 4 14 9 6
生成的 DataFrame 按分数降序排序,然后按索引升序排序(如果有两个玩家得分相同)。
请注意,如果我们不使用升序参数,则每列将使用升序作为默认排序方法:
#sort by points and then by index df. sort_values (by = [' points ', ' id ']) points assists rebounds id 4 14 9 6 2 15 7 8 3 15 7 10 5 20 12 6 6 20 9 5 1 25 5 11 7 25 9 9 8 29 4 12
如果索引列当前未命名,您可以对其进行重命名,然后进行相应的排序:
#sort by points and then by index df. rename_axis (' index '). sort_values (by = [' points ', ' id ']) points assists rebounds id 4 14 9 6 2 15 7 8 3 15 7 10 5 20 12 6 6 20 9 5 1 25 5 11 7 25 9 9 8 29 4 12