【问题标题】:delete rows based on a condition in pandas根据熊猫中的条件删除行
【发布时间】:2020-09-20 18:32:57
【问题描述】:

我有以下数据框

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

基本上我可以过滤如下行

df[df["coverage"] > 30

我可以如下删除/删除一行

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

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

【问题讨论】:

  • 你能解释一下你的情况吗?
  • 如果coverage列的值小于72,我想删除行
  • 然后使用布尔索引 - df[df["coverage"] >= 72]
  • 是的,我知道了,只是想知道我是否可以找到更多方法,所以在这里发布:)

标签: python pandas


【解决方案1】:

最好的是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函数:

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

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

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

【讨论】:

    【解决方案2】:

    我们也可以使用 pandas.query() 功能

    import pandas as pd 
    
    dict_ = {'coverage':[45,214,212,72,85], 'name': ['jason','Molly','Tina','Jake','Amy']}
    df  = pd.DataFrame(dict_)
    
    print(df.query('coverage > 72'))
    

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      相关资源
      最近更新 更多