1

Although there are several related questions answered in Pandas, I cannot solve this issue. I have a large dataframe (~ 49000 rows) and want to drop rows the meet two conditions at the same time(~ 120):

  • For one column: an exact string
  • For another column: a NaN value

My code is ignoring the conditions and no row is removed.

to_remove = ['string1', 'string2'] 
df.drop(df[df['Column 1'].isin(to_remove) & (df['Column 2'].isna())].index, inplace=True)

What am I doing wrong? Thanks for any hint!

0

1 Answer 1

3

Instead of calling drop, and passing the index, You can create the mask for the condition for which you want to keep the rows, then take only those rows. Also, the logic error seems to be there, you are checking two different condition combined by AND for the same column values.

df[~(df['Column1'].isin(to_remove) & (df['Column2'].isna()))]

Also, if you need to check in the same column, then you probably want to combine the conditions by or i.e. | If needed, you can reset_index at last.

Also, as side note, your list to_remove has two same string values, I'm assuming thats a typo in the question.

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

5 Comments

This works but does not totally answers OP question. Why does his drop method do not work ?
@BenjaminRio I was updating the answer, thanks for your comment.
df['Column2'].isna() doesn't need to be wrapped in parentheses.
@fsimonjetz Yes it doesn't I just copied and pasted what OP had mentioned
I removed the typos in the question. Will check your proposed solutions. Mask method I tried before but did not solved my issue.

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.