如何对Pandas数据框架进行排序
本文将讨论如何在Python中使用各种方法对Pandas DataFrame进行排序。
创建一个数据框架,用于去污
# importing pandas library
import pandas as pd
# creating and initializing a nested list
age_list = [['Afghanistan', 1952, 8425333, 'Asia'],
['Australia', 1957, 9712569, 'Oceania'],
['Brazil', 1962, 76039390, 'Americas'],
['China', 1957, 637408000, 'Asia'],
['France', 1957, 44310863, 'Europe'],
['India', 1952, 3.72e+08, 'Asia'],
['United States', 1957, 171984000, 'Americas']]
# creating a pandas dataframe
df = pd.DataFrame(age_list, columns=['Country', 'Year',
'Population', 'Continent'])
df
输出 :
对Pandas数据框架进行排序
对Pandas数据帧进行排序
为了在pandas中对数据框进行排序,使用了sort_values()函数。Pandas sort_values()可以对数据框进行升序或降序排序。
例子1:以升序排列数据框
# Sorting by column 'Country'
df.sort_values(by=['Country'])
输出 :
对Pandas数据框架进行排序
例子2:以降序排序数据框
# Sorting by column "Population"
df.sort_values(by=['Population'], ascending=False)
输出 :
对Pandas数据框架进行排序
实例3:通过将缺失值放在前面来对Pandas数据框架进行排序
# Sorting by column "Population"
# by putting missing values first
df.sort_values(by=['Population'], na_position='first')
输出 :
对Pandas数据框架进行排序
例子4:按多列对数据框架进行排序
# Sorting by columns "Country" and then "Continent"
df.sort_values(by=['Country', 'Continent'])
输出 :
对Pandas数据框架进行排序
例子5:按多列但不同顺序对数据帧进行排序
# Sorting by columns "Country" in descending
# order and then "Continent" in ascending order
df.sort_values(by=['Country', 'Continent'],
ascending=[False, True])
输出:
对Pandas数据框架进行排序