map str.contains across pandas DataFrame
There are many ways to do this. One way to do it would be the following:
def like_function(x):
group = "unknown"
for key in product_map:
if key in x:
group = product_map[key]
break
return group
df['company'] = df.comp.apply(like_function)
A vectorized solution inspired by MaxU's solution to a similar problem.
x = df.comp.str.split(expand=True)
df['company'] = None
df['company'] = df['company'].fillna(x[x.isin(product_map.keys())]\
.ffill(axis=1).bfill(axis=1).iloc[:, 0])
df['company'].replace(product_map, inplace=True)
print(df)
# comp price company
#0 dell notebook 0 Dell Inc.
#1 dell notebook S3 1 Dell Inc.
#2 dell notepad 2 Dell Inc.
#3 apple ipad 3 Apple Inc.
#4 apple ipad2 4 Apple Inc.
#5 acer chromebook 5 Acer Inc.
#6 acer chromebookx 6 Acer Inc.
#7 mac air 7 Apple Inc.
#8 mac pro 8 Apple Inc.
#9 lenovo x4 9 Dell Inc.