Python Pandas match exact pattern

Viewed 76

I'm trying to match a pattern with a column of a dataframe

pattern='pgk'
df = pd.DataFrame([['merged_pgk', 10], ['merged_Pgk', 3], ['merged_pgk_stim', 12], ['merged_Scp1', 5]], columns=['condition','count'])

I want the row where pattern is in the column condition.

df[df['condition'].str.lower().str.contains(pattern)]

I tried this but the problem here is that it will return pgk row (what I want) but I got also pgk_stim row (what I don't want)

2 Answers

try np.where with str.contains and case=False to ignore the case.

and $ to only match pgk at the end of a string.

df['check'] = np.where(df['condition'].str.contains('pgk$',case=False), True,False)

print(df)

         condition  count  check
0       merged_pgk     10   True
1       merged_Pgk      3   True
2  merged_pgk_stim     12  False
3      merged_Scp1      5  False

you can use endswith function df[df['condition'].str.lower().str.endswith(pattern)]

Related