根据 pandas 中的条件删除行 [英] delete rows based on a condition in pandas

查看:109
本文介绍了根据 pandas 中的条件删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框

In [62]: df
Out[62]:
            coverage   name  reports  year
Cochice           45  Jason        4  2012
Pima             214  Molly       24  2012
Santa Cruz       212   Tina       31  2013
Maricopa          72   Jake        2  2014
Yuma              85    Amy        3  2014

基本上,我可以按如下所述过滤行

Basically i can filter the rows as below

df[df["coverage"] > 30

我可以如下所示删除/删除单行

and i can drop/delete a single row as below

df.drop(['Cochice', 'Pima'])

但是我想根据条件删除一定数量的行,我该怎么做?

But i want to delete a certain number of rows based on a condition, how can i do so?

推荐答案

最好是 boolean indexing ,但需要取反条件-将所有值等于和大于72:

print (df[df["coverage"] >= 72])
            coverage   name  reports  year
Pima             214  Molly       24  2012
Santa Cruz       212   Tina       31  2013
Maricopa          72   Jake        2  2014
Yuma              85    Amy        3  2014

它与 ge 功能:

It is same as ge function:

print (df[df["coverage"].ge(72)])
            coverage   name  reports  year
Pima             214  Molly       24  2012
Santa Cruz       212   Tina       31  2013
Maricopa          72   Jake        2  2014
Yuma              85    Amy        3  2014

另一种可能的解决方案是通过~反转掩码:

Another possible solution is invert mask by ~:

print (df["coverage"] < 72)
Cochice        True
Pima          False
Santa Cruz    False
Maricopa      False
Yuma          False
Name: coverage, dtype: bool

print (~(df["coverage"] < 72))
Cochice       False
Pima           True
Santa Cruz     True
Maricopa       True
Yuma           True
Name: coverage, dtype: bool


print (df[~(df["coverage"] < 72)])
            coverage   name  reports  year
Pima             214  Molly       24  2012
Santa Cruz       212   Tina       31  2013
Maricopa          72   Jake        2  2014
Yuma              85    Amy        3  2014

这篇关于根据 pandas 中的条件删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆