Exact match in Pandas Series after splitting by character

Question:

Given the following Pandas Series:

import pandas as pd
series = pd.Series(['red', 'green,blue', 'yellow', 'greenish', 'blueish'])

How to find the index (or boolean) where, after splitting each element by the character ‘,’, there is an exact match for any given string?

For example, the strings ‘green’ and ‘blue’ should both have a unique match at index 1.

Asked By: David

||

Answers:

I would do it following way

import pandas as pd
series = pd.Series(['red', 'green,blue', 'yellow', 'greenish', 'blueish'])
green = series.str.split(',').apply(lambda x:"green" in x)
print(green)

gives output

0    False
1     True
2    False
3    False
4    False
dtype: bool

Explanation: str.split at , to get lists then use apply and lambda to check if list contains "green".

Answered By: Daweo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.