Pandas怎樣按條件刪除行?

來自:
https://stackoverflow.com/questions/13851535/delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression-involvingexpress

To directly answer this question's original title "How to delete rows from a pandas DataFrame based on a conditional expression" (which I understand is not necessarily the OP's problem but could help other users coming across this question) one way to do this is to use the drop method:this

df = df.drop(some labels)

df = df.drop(df[<some boolean condition>].index)

Examplecode

To remove all rows where column 'score' is < 50:ip

df = df.drop(df[df.score < 50].index)

In place version (as pointed out in comments)rem

df.drop(df[df.score < 50].index, inplace=True)

Multiple conditionsget

(see Boolean Indexing)pandas

The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.it

To remove all rows where column 'score' is < 50 and > 20io

df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
相關文章
相關標籤/搜索