48

I tried drop method of pandas but I didn't use it. How do I remove a specific row in pandas with Python?

e.g.: My specific row is => Name: Bertug Grade: A Age: 15

4 Answers 4

56
df = pd.DataFrame([['Jhon',15,'A'],['Anna',19,'B'],['Paul',25,'D']])
df. columns = ['Name','Age','Grade']

df
Out[472]: 
   Name  Age Grade
0  Jhon   15     A
1  Anna   19     B
2  Paul   25     D

You can get the index of your row:

i = df[((df.Name == 'jhon') &( df.Age == 15) & (df.Grade == 'A'))].index

and then drop it:

df.drop(i)
Out[474]: 
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D

As @jezrael pointed our, you can also just negate all three:

df[((df.Name != 'jhon') &( df.Age != 15) & (df.Grade != 'A'))]
Out[477]: 
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D
Sign up to request clarification or add additional context in comments.

2 Comments

There's mistake in the negation. The negation of A and B is ~A or ~B. I added an answer here that shows the correct negation.
Beautiful to see that the De Morgan's Law is alive and well.
35

you can just use :

df.drop([a,b,c])

where a,b,c are the list of indexes or row numbers.

to delete only one particular row use

df.drop(i)

where i is the index or the row number.

2 Comments

You should assign to the new df, or just add inplace=True in drop command section. Without these, you could not use dropped version.
Yes. print(df.drop(i)) works but does not affect df. df = df.drop(i) or the like does affect.
2

Dropping rows is the inverse operation of filtering rows you want to keep, so a negating a boolean mask that filters for the rows to drop is enough.

df[~(df['Name'].eq('Bertug') & df['Grade'].eq('A') & df['Age'].eq(15))]

which is, by de Morgan's laws, equivalent to

df[df['Name'].ne('Bertug') | df['Grade'].ne('A') | df['Age'].ne(15))]

Another approach is to simply query the rows you want to keep.

df1 = df.query("not (Name == 'Bertug' and Grade == 'A' and Age == 15)")
# or 
df1 = df.query("Name != 'Bertug' or Grade != 'A' or Age != 15")

If the index of the row(s) to be dropped are given, then query (or drop) can be used too. For example, the following drops the second row.

idx = [1]
df1 = df.query("index != @idx")

# equivalently,
df1 = df.drop(idx)

Comments

2

you can drop just by writing this where df is your DataFrame and in index write the index of the row you want to drop df.drop(index=0, inplace=True)

1 Comment

Thank you for your contribution. However, your answer does not provide anything substantial new. If you create an answer for a question that already has a high-rated answer, please think twice if your answer really adds something substantial new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.