2

In the following pandas dataframe, In the following, I want the data for ID 1 only and drop rest of the data. How to achieve that?

ID   name  s1       s2       s3       s4

1   Joe   rd       fd       NaN      aa
1   Joe   NaN      hg       kk       NaN
2   Ann   jg       hg       zt       uz
2   Mya   rd       fd       NaN      aa
1   Uri   gg       r        er       rt
4   Ron   hr       t        yt       rt
1
  • df[df['ID'] == 1] Commented Feb 22, 2020 at 20:17

2 Answers 2

3

All dataframes have a drop method which can do what you want.

For your specific case, if you really want to drop the data instead of filtering it to a different dataframe, then the following snippet:

df.drop(df[df['ID'] != 1].index, inplace = True)

Should work.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it worked. Can I ask why have you used ".index" here?
From the documentation, the DataFrame.drop() method accepts either index (to drop entire rows) or column labels (to drop columns). Since you wanted to drop entire rows, we needed to use index.
This is inefficient
Why not: df[df.ID==1]
2

Use boolean índexing

 df.loc[df['ID'].eq(1)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.