Home > other >  Removing rows from a pandas dataframe if a column contains a particular word alone
Removing rows from a pandas dataframe if a column contains a particular word alone

Time:03-17

I am working on a pandas dataframe from which i have to remove rows if it contains a particular word alone. For example,

df = pd.DataFrame({'team': ['Team 1', 'Team 1 abc', 'Team 2',
                            'Team 3', 'Team 2', 'Team 3'],
                   'Subject': ['Math', 'Science', 'Science', 
                               'Math', 'Science', 'Math'],
                   'points': [10, 8, 10, 6, 6, 5]})

I tried to remove rows which contain Team 1 alone. For that I tried,

df = df[df["team"].str.contains("Team 1") == False]

and I got the dataframe like

enter image description here

The dataframe I needed as follows with row number also should be in order

enter image description here

CodePudding user response:

Just use != instead of .str.contains:

df = df[df["team"] != "Team 1"]

Output:

>>> df
         team  Subject  points
1  Team 1 abc  Science       8
2      Team 2  Science      10
3      Team 3     Math       6
4      Team 2  Science       6
5      Team 3     Math       5
  • Related