Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

How to assign the label 1 to rows which satisfy the below following conditions:

  • If the Word column contains Amber or Light or Yellow then it has to be 1;
  • else it has to be 0

I have tried the following:

df[(df.Word=='Amber') & (df.Word=='Light') & (df.Word=='Yellow') ]['IND'] = 1 but it does not work

1 Answer

0 votes
by (36.8k points)
edited by

You have one problem in the chain slice assign to fix your code

df['IND'] = 0

df.loc[df['Word'].isin(['Amber','Light', 'Yellow']),'IND'] = 1

However we usually do like this:

df['IND'] = np.where(df['Word'].isin(['Amber','Light', 'Yellow']), 1 ,0 )

Or

df['IND'] = df['Word'].isin(['Amber','Light', 'Yellow']).astype(int)

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...