如何通过列值的条件在DataFrame中删除行 您所在的位置:网站首页 如何删除符合条件的行列 如何通过列值的条件在DataFrame中删除行

如何通过列值的条件在DataFrame中删除行

2024-04-28 21:09| 来源: 网络整理| 查看: 265

如何通过列值的条件在DataFrame中删除行

在这篇文章中,我们将看到几个例子,说明如何根据应用于某一列的某些条件从数据框架中删除行。

Pandas为数据分析师提供了一种使用dataframe.drop()方法来删除和过滤数据帧的方法。我们可以使用这个方法来删除这些不满足给定条件的行。

让我们创建一个Pandas数据框架。

# import pandas library import pandas as pd    # dictionary with list object in values details = {     'Name' : ['Ankit', 'Aishwarya', 'Shaurya',               'Shivangi', 'Priya', 'Swapnil'],     'Age' : [23, 21, 22, 21, 24, 25],     'University' : ['BHU', 'JNU', 'DU', 'BHU',                      'Geu', 'Geu'], }    # creating a Dataframe object  df = pd.DataFrame(details, columns = ['Name', 'Age',                                       'University'],                   index = ['a', 'b', 'c', 'd', 'e',                            'f'])    df

输出:

如何通过列值的条件在DataFrame中删除行?

例子1:根据某一列的条件删除行。

# import pandas library import pandas as pd    # dictionary with list object in values details = {     'Name' : ['Ankit', 'Aishwarya', 'Shaurya',               'Shivangi', 'Priya', 'Swapnil'],     'Age' : [23, 21, 22, 21, 24, 25],     'University' : ['BHU', 'JNU', 'DU', 'BHU',                      'Geu', 'Geu'], }    # creating a Dataframe object  df = pd.DataFrame(details, columns = ['Name', 'Age',                                       'University'],                   index = ['a', 'b', 'c', 'd', 'e', 'f'])    # get names of indexes for which # column Age has value 21 index_names = df[ df['Age'] == 21 ].index    # drop these row indexes # from dataFrame df.drop(index_names, inplace = True)    df

输出 :

如何通过列值的条件在DataFrame中删除行?

例子2:根据一列的多个条件删除行。

# import pandas library import pandas as pd    # dictionary with list object in values details = {     'Name' : ['Ankit', 'Aishwarya', 'Shaurya',                'Shivangi', 'Priya', 'Swapnil'],     'Age' : [23, 21, 22, 21, 24, 25],     'University' : ['BHU', 'JNU', 'DU', 'BHU',                     'Geu', 'Geu'], }    # creating a Dataframe object  df = pd.DataFrame(details, columns = ['Name', 'Age',                                       'University'],                   index = ['a', 'b', 'c', 'd', 'e', 'f'])    # get names of indexes for which column Age has value >= 21 # and = 21) & (df['Age'] = 21 # and column University is BHU index_names = df[ (df['Age'] >= 21) & (df['University'] == 'BHU')].index    # drop these given row # indexes from dataFrame df.drop(index_names, inplace = True)    df

输出 :

如何通过列值的条件在DataFrame中删除行?



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有