TourEiffel
TourEiffel

Reputation: 4434

Delete pandas dataframe row based on multiple condition

I have the following df :

ABF2
ABG2
ABH2
ABJ3
ABK4
ABM5
ABN6
ABQ7

My goal is to have the following data frame :

ABH2
ABM5
ABQ7

So basically the condition would be multiple :

if third char = H, M, Q or Z

To get the third char value I do as below :

DF.Col_Name[2::2]

Fact is that I don't really know how to apply multiple condition to retrieve the wanted DF. Also, what would be the quickest way to do this ?

Upvotes: 0

Views: 39

Answers (3)

jezrael
jezrael

Reputation: 863501

Select third character with str and test values in Series.isin for test by membership, filter by boolean indexing:

df = DF[DF.Col_Name.str[2].isin(['H','M','Q','Z'])]

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

You can try .str accessor

out = df[df['col'].str[2].isin(['H', 'M', 'Q', 'Z'])]
print(out)

    col
2  ABH2
5  ABM5
7  ABQ7

Upvotes: 1

sophocles
sophocles

Reputation: 13841

You can use:

df.loc[df.col.str[2].str.contains('H|M|Q|Z')]

prints:

    col
2  ABH2
5  ABM5
7  ABQ7

Upvotes: 1

Related Questions