Reputation: 53
I'm trying to test if one column (surname) is a substring of another column (name) in a dataframe (el). I've tried the following but python doesn't like it
el.name.str.contains(el.surname)
I can see plenty of examples of how to search for a literal substring, but not where the substring is a column. Going mad on this one, help please!
Dave
Upvotes: 3
Views: 2029
Reputation: 43169
You may use
import pandas as pd
dct = {'surname': ['Smith', 'Miller', 'Mayer'],
'name': ['Dr. John Smith', 'Nobody', 'Prof. Dr. Mayer']}
df = pd.DataFrame(dct)
df['is_part_of_name'] = df.apply(lambda x: x["surname"] in x["name"], axis=1)
print(df)
Which yields
surname name is_part_of_name
0 Smith Dr. John Smith True
1 Miller Nobody False
2 Mayer Prof. Dr. Mayer True
Upvotes: 4