Home > Enterprise >  Pandas Dataframe Remove all Rows with Letters in Certain Column
Pandas Dataframe Remove all Rows with Letters in Certain Column

Time:11-17

I have a pandas dataframe in python that I want to remove rows that contain letters in a certain column. I have tried a few things, but nothing has worked.

Input:

A B C
0 9 1 a
1 8 2 b
2 7 cat c
3 6 4 d

I would then remove rows that contained letters in column 'B'...

Expected Output:

A B C
0 9 1 a
1 8 2 b
3 6 4 d

CodePudding user response:

Assuming the B column be string type, we can use str.contains here:

df[~df["B"].str.contains(r'^[A-Za-z] $', regex=True)]

CodePudding user response:

here is another way to do it

# use isalpha to check if value is alphabetic
# use negation to pick where value is not alphabetic

df.loc[~df['B'].str.isalpha()]

    A   B   C
0   9   1   a
1   8   2   b
3   6   4   d
  • Related