在pandas DataFrame中对行进行排序

在pandas DataFrame中对行进行排序

Pandas DataFrame是二维的大小可变的,可能是异质的表格数据结构,有标记的轴(行和列)。在处理数据时,我们经常需要对行和列做某些操作。

让我们看看如何对pandas DataFrame中的行进行排序。

代码#1:按科学排序的行数

# import modules
import pandas as pd
  
# create dataframe
data = {'name': ['Simon', 'Marsh', 'Gaurav', 'Alex', 'Selena'], 
        'Maths': [8, 5, 6, 9, 7], 
        'Science': [7, 9, 5, 4, 7],
        'English': [7, 4, 7, 6, 8]}
  
df = pd.DataFrame(data)
  
# Sort the dataframe’s rows by Science,
# in descending order
a = df.sort_values(by ='Science', ascending = 0)
print("Sorting rows by Science:\n \n", a)
Python

输出:

Sorting rows by Science:

    English  Maths  Science    name
1        4      5        9   Marsh
0        7      8        7   Simon
4        8      7        7  Selena
2        7      6        5  Gaurav
3        6      9        4    Alex
Python

代码#2:按数学排序行,然后按英语排序行。

# import modules
import pandas as pd
  
# create dataframe
data = {'name': ['Simon', 'Marsh', 'Gaurav', 'Alex', 'Selena'], 
        'Maths': [8, 5, 6, 9, 7], 
        'Science': [7, 9, 5, 4, 7],
        'English': [7, 4, 7, 6, 8]}
  
df = pd.DataFrame(data)
  
# Sort the dataframe’s rows by Maths
# and then by English, in ascending order
b = df.sort_values(by =['Maths', 'English'])
print("Sort rows by Maths and then by English: \n\n", b)
Python

输出:

Sort rows by Maths and then by English: 

    English  Maths  Science    name
1        4      5        9   Marsh
2        7      6        5  Gaurav
4        8      7        7  Selena
0        7      8        7   Simon
3        6      9        4    Alex
Python

代码#3:如果你想先获得缺失值。

import pandas as pd
  
# create dataframe
data = {'name': ['Simon', 'Marsh', 'Gaurav', 'Alex', 'Selena'], 
        'Maths': [8, 5, 6, 9, 7], 
        'Science': [7, 9, 5, 4, 7],
        'English': [7, 4, 7, 6, 8]}
df = pd.DataFrame(data)
  
  
a = df.sort_values(by ='Science', na_position ='first' )
print(a)
Python

输出:

English  Maths  Science    name
3        6      9        4    Alex
2        7      6        5  Gaurav
0        7      8        7   Simon
4        8      7        7  Selena
1        4      5        9   Marsh
Python

由于本例中没有缺失值,因此将产生与上述相同的输出,但以升序排序。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册