Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

How to drop rows with respect to a column values in Python?

I wantto remove rows with respect ID column values.

df

   ID    B   C   D
0  101   1   2   3
1  103   5   6   7
2  108   9  10  11
3  109   5   3  12
4  118  11  15   2
5  121   2   5   6

Here the remove_id list of ID value those I want to remove.

remove_id = [103,108, 121]

I want to output like following:

df

   ID    B   C   D
0  101   1   2   3
3  109   5   3  12
4  118  11  15   2

How can I do this?

Upvotes: 0

Views: 44

Answers (1)

timgeb
timgeb

Reputation: 78690

You can check which IDs are in remove_id with the isin method, negate the result with ~ and use the resulting Series for boolean indexing.

>>> df[~df['ID'].isin(remove_id)]
>>> 
    ID   B   C   D
0  101   1   2   3
3  109   5   3  12
4  118  11  15   2

Details:

>>> df['ID'].isin(remove_id)
>>> 
0    False
1     True
2     True
3    False
4    False
5     True
Name: ID, dtype: bool
>>> ~df['ID'].isin(remove_id)
>>> 
0     True
1    False
2    False
3     True
4     True
5    False
Name: ID, dtype: bool

Upvotes: 1

Related Questions