1

I'm trying to drop rows in a pandas dataframe on an exact match. My code nearly works, but it currently drops rows which match partially (which I don't want).

The code below will drop the name 'Krish' from the dataframe because it partially matches to 'kris'.

import pandas as pd

# list of strings to drop in an exact match
drop_list = ["nick", "kris"]

# initialize data of lists.
data = {'Name': ['Tom', 'nick', 'krish', 'jack'],
        'Age': [20, 21, 19, 18]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['Name'].str.contains("|".join(drop_list))]

# print dataframe.
print(df)

Current Output:

   Name  Age
0   Tom   20
3  jack   18

Desired Output:

    Name  Age
0    Tom   20
2  krish   19
3   jack   18
Lee Roy
  • 297
  • 1
  • 11
  • [Series.isin](https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html) -> `df = df[~df['Name'].isin(drop_list)]` – Henry Ecker Feb 10 '22 at 19:18

1 Answers1

3

Use isin:

df = df[~df['Name'].isin(drop_list)]

Output:

>>> df
    Name  Age
0    Tom   20
2  krish   19
3   jack   18