xxxvinxxx xxxvinxxx - 8 months ago 44
Python Question

Pandas and apply function to match a string

I have a df column containing various links, some of them containing the string


I want to create a function that - being applied to the column - returns a column containing

I write a function like:

search = 'search'
def page_type(x):
if x.str.contains(search):
return 'Search'
return 'Other'


but it gives me an error like:

AttributeError: 'unicode' object has no attribute 'str'

I guess I'm missing something when calling the str.contains().


.str applies to the whole Series but here you are dealing with the value inside the Series.

You can either do : df['link'].str.contains(search)
Or like you want : df['link'].apply(lambda x: 'Search' if search in x else 'Other')


More generic way:

def my_filter(x, val, c_1, c_2):
    return c_1 if val in x else  c_2 

df['link'].apply(lambda x: my_filter(x, 'homepage', 'homepage', 'other'))