Napier
Napier

Reputation: 227

Create new column based on text condition

I want to make new column based on another columns with text

Let say, I have this column

    Name
Acer aspire 1
Acer spin
Dell alienware
Dell 2-in-1
MSI thin
Asus flip
MSI flip

to be like this

    Name           touchscreen
Acer aspire 1     No
Acer spin         Yes
Dell alienware    No
Dell 2-in-1       Yes
MSI thin          No
Asus flip         Yes
MSI flip          Yes

and the condition is, if in the column consist "spin", "2-in-1", "flip", then it is yes, but if it isn't, then it is no

Upvotes: 0

Views: 58

Answers (1)

jezrael
jezrael

Reputation: 862641

Use numpy.where with Series.str.contains, for regex or is used |:

df['touchscreen'] = np.where(df['Name'].str.contains('spin|flip|2-in-1'), 'Yes', 'No')
print (df)
             Name touchscreen
0   Acer aspire 1          No
1       Acer spin         Yes
2  Dell alienware          No
3     Dell 2-in-1         Yes
4        MSI thin          No
5       Asus flip         Yes
6        MSI flip         Yes

Upvotes: 1

Related Questions