1

How can I create a python statement for a conditional

I have a dataframe like

Day   Weather   Indicator
1     Sunny     No 
2     Sunny     No
3     Dark      No
7     Dark      No

How can I create an conditional that lets me know if day=7 then create a new column

Day   Weather   Indicator
1     Sunny     No 
2     Sunny     No
3     Dark      No
7     Dark      Yes

2 Answers 2

3

Use numpy.where:

df['Indicator'] = np.where(df['Day'] == 7, 'Yes','No')

EDIT:

If exist Indicator column filled Novalues - mask or loc working nice for select rows by condition:

df['Indicator'] = df['Indicator'].mask(df['Day'] == 7, 'Yes')

df.loc[df['Day'] == 7, 'Indicator'] = 'Yes'
print (df)
   Day Weather Indicator
0    1   Sunny        No
1    2   Sunny        No
2    3    Dark        No
3    7    Dark       Yes
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Jezrael, I edited the input column do you think you can help with the modified input statement please?
Solution is not necessary modify, working nice too. But if exist column filled No, then df['Indicator'] = df['Indicator'].mask(df['Day'] == 7, 'Yes') also working.
1

assign +eq

df.assign(Indicator=df.Day.eq(7).map({1:'Yes',0:'No'}))

2 Comments

Or df['Indicator'] = df['Day'].eq(7).map({True:'Yes', False:'No'}), feel free add it to your answer
@jezrael I will keep here :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.