user3657850
user3657850

Reputation: 552

Delete Row from Pandas DataFrame based on cell value

How can i delete a row in a Pandas Dataframe, based on a cell value without giving a specific column name?

For example:

I have this DataFrame and i want to delete all rows where a cell contains the value 'd'.

   A B C D
1  1 2 d 5
2  1 3 4 0
3  d 2 1 2
4  3 2 1 7

So I end up with the DataFrame

  A B C D
2 1 3 4 0
4 3 2 1 7

Is there a way to achive this? My google skills only found solutions where a specific column name is required.

Upvotes: 4

Views: 2917

Answers (2)

Scott Boston
Scott Boston

Reputation: 153510

Another way you could do it to use astype, ne and all:

df[df.astype(str).ne('d').all(axis=1)]

Output:

   A  B  C  D
2  1  3  4  0
4  3  2  1  7

Another way:

df.where(df.values != 'd').dropna()

Output:

   A  B  C  D
2  1  3  4  0
4  3  2  1  7

Upvotes: 3

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210972

you can do it this way:

df = df[~df.select_dtypes(['object']).eq('d').any(1)]

Result:

In [23]: df
Out[23]:
   A  B  C  D
2  1  3  4  0
4  3  2  1  7

Upvotes: 5

Related Questions