Home > Mobile >  python pandas 'reverse' substring search
python pandas 'reverse' substring search

Time:02-17

Given a long string name = 'Mary had a little lamb'

and a pandas Series with pd.Series(data=['Mary', 'large', 'little lamb']) ,

is there a pandas string operation that could identify whether an entry is a substring of the longer string name ?

CodePudding user response:

No, I don't think there is one. You would need to iterate:

s = pd.Series(data=['Mary', 'large', 'little lamb'])
name = 'Mary had a little lamb'

[x in name for x in s]

output: [True, False, True]

CodePudding user response:

You can loop through the different items in the Series using for-loops (or list comprehensions to make it more concise) and check if each item is in the long string using in:

name = 'Mary had a little lamb'
for string in pd.Series(data=['Mary', 'large', 'little lamb']):
    if string in name:
        print(f"'{string}' is in long string")
    else:
        print(f"'{string}' is not  long string")

Output:

'Mary' is in long strong
'large' is not  long strong
'little lamb' is in long strong
  • Related