从Pandas DataFrame中删除一个行的列表

从Pandas DataFrame中删除一个行的列表

让我们看看如何在Pandas DataFrame中删除一个行的列表。我们可以使用Pandas drop()函数来做到这一点。我们还将传递 inplace = True 和 axis=0 来表示行,因为它使我们在实例中所做的改变存储在该实例中,而不做任何赋值。

创建Dataframe来丢弃一个行的列表

# import the module
import pandas as pd
 
# creating a DataFrame
dictionary = {'Names': ['Simon', 'Josh', 'Amen', 'Habby',
                        'Jonathan', 'Nick'],
              'Countries': ['AUSTRIA', 'BELGIUM', 'BRAZIL',
                            'FRANCE', 'INDIA', 'GERMANY']}
table = pd.DataFrame(dictionary, columns=['Names', 'Countries'],
                     index=['a', 'b', 'c', 'd', 'e', 'f'])
 
display(table)
Python

输出:

从Pandas DataFrame中删除一个行的列表

使用df.drop从Pandas数据框架中删除一个行列表

在这个例子中,我们只是删除了索引为3的那一行。

# drop 3rd row
display("Dropped 3rd row")
display(table.drop('c'))
Python

从pandas中删除行而不提索引标签

在这里,我们只是从Dataframe表中删除第1和第3行。一开始,我们使用索引值丢弃,之后,我们使用行名来丢弃该行。

# gives the table with the dropped rows
display("Table with the dropped rows")
display(table.drop(table.index[[1, 3]]))
 
# You can also use index no. instead rows name
# display(table.drop(['a', 'd']))
Python

输出:

从Pandas DataFrame中删除一个行的列表

使用inplace从Pandas DataFrame中删除一个行的列表

在这个例子中,我们正在丢弃有inplace和没有inplace的行。在这里,我们使用inplace=True,在同一个Dataframe中执行丢弃操作,而不是在丢弃操作中创建一个新的Dataframe对象。

table = pd.DataFrame(dictionary, columns=['Names', 'Countries'],
                     index=['a', 'b', 'c', 'd', 'e', 'f'])
 
# it gives none but it makes changes in the table
display(table.drop(['a', 'd'], inplace=True))
 
# final table
print("Final Table")
display(table)
Python

输出:

从Pandas DataFrame中删除一个行的列表

在Pandas数据框架中按索引范围删除行

该范围的下限和上限分别是包容和排斥的。因此,第0和第1行将被删除,但第2行不会被删除。

# table after removing range of rows from 0 to 2(not included)
table.drop(table.index[0:2], inplace=True)
 
display(table)
Python

输出:

从Pandas DataFrame中删除一个行的列表

在Pandas中用条件删除行

Dataframe中的Josh名字根据条件被丢弃,如果df[‘Names’] == ‘Josh’],那么丢弃该行。你可以通过相同的语法,用更多的条件放弃多条记录。

df = table
index_names = df[ df['Names'] == 'Josh'].index
   
# drop these row indexes
# from dataFrame
df.drop(index_names, inplace = True)
 
display(table)
Python

输出:

从Pandas DataFrame中删除一个行的列表

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册