Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

python - delete rows based on a condition in pandas

I have the below dataframe

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best is boolean indexing but need invert condition - get all values equal and higher as 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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...