如何根据列名或行索引对Pandas数据框架进行排序
Pandas dataframe.sort_index()方法按照给定axis的标签对对象进行排序。基本上,排序算法是应用于axis的标签,而不是Dataframe中的实际数据,并在此基础上重新排列数据。
创建Pandas的数据框架
从带有列和索引的Python图元列表中创建一个DataFrame对象,例如列名是。’姓名’、’年龄’、’地点’和’学院’。
# import pandas library as pd
import pandas as pd
# List of Tuples
students = [('Ankit', 22, 'Up', 'Geu'),
('Ankita', 31, 'Delhi', 'Gehu'),
('Rahul', 16, 'Tokyo', 'Abes'),
('Simran', 41, 'Delhi', 'Gehu'),
('Shaurya', 33, 'Delhi', 'Geu'),
('Harshita', 35, 'Mumbai', 'Bhu' ),
('Swapnil', 35, 'Mp', 'Geu'),
('Priya', 35, 'Uk', 'Geu'),
('Jeet', 35, 'Guj', 'Gehu'),
('Ananya', 35, 'Up', 'Bhu')
]
# Create a DataFrame object from
# list of tuples with columns
# and indices.
details = pd.DataFrame(students, columns =['Name', 'Age',
'Place', 'College'],
index =[ 'b', 'c', 'a', 'e', 'f', 'g',
'i', 'j', 'k', 'd'])
# show the dataframe
details
输出:
根据行索引对数据框架进行排序
示例1:根据行索引标签名称对数据框架的行进行排序,即行索引:a、b、c、d等。
# import pandas library as pd
import pandas as pd
# sort the rows of dataframe
# based on row index
rslt_df = details.sort_index()
# show the resultant Dataframe
rslt_df
输出:
示例2:根据行索引标签对数据框架的行进行降序排序。
# import pandas library as pd
import pandas as pd
# sort the rows of dataframe in descending
# order based on row index
rslt_df = details.sort_index(ascending = False)
# show the resultant Dataframe
rslt_df
输出:
示例3:根据行索引标签inplace=True对数据框架的行进行排序。它将应用原始数据框架中的过滤器。
# import pandas library as pd
import pandas as pd
# sort the rows of dataframe in Place
# based on row index
details.sort_index(inplace = True)
# show the resultant Dataframe
details
输出:
根据列名对数据框架进行排序
例子1:根据列名对数据框架的列名进行排序,即年龄、学院、姓名、地点。
# import pandas library as pd
import pandas as pd
# sort a dataframe based on column names
rslt_df = details.sort_index(axis = 1)
# show the resultant Dataframe
rslt_df
输出:
例子2:根据列名对数据框架进行降序排序。
# import pandas library as pd
import pandas as pd
# sort a dataframe in descending
# order based on column names
rslt_df = details.sort_index(ascending = False, axis = 1)
# show the resultant Dataframe
rslt_df
输出:
示例3:根据列名对数据框架进行就地排序。
# import pandas library as pd
import pandas as pd
# sort a dataframe in place
# based on column names
details.sort_index(inplace = True, axis = 1)
# show the resultant Dataframe
details
输出: