Just use np.where:
import numpy as np
df['Y'] = np.where(df['X'].ge(5),1,df['Y'])
df['Y'] = np.where(df['X'].le(-5),0,df['Y'])
Even better, for multiple conditions, use np.select:
conditions=[df['X'].ge(5),df['X'].le(-5)]
choices=[1,0]
df['Y']=np.select(conditions,choices,default=df['Y'])
Or, if you only want to do it with a list comprehension, use zip:
df['Y'] =[1 if x>=5 else(0 if x<=-5 else y)for x,y in zip(df['X'],df['Y'])]
Output:
original df
X X2 Y
0 -6 11 1
1 -10 10 0
2 6 15 1
3 9 12 0
4 -2 3 1
5 -5 2 0
6 5 6 1
7 -1 12 0
8 7 10 0
9 -6 9 0
df after np.where
X X2 Y
0 -6 11 0
1 -10 10 0
2 6 15 1
3 9 12 1
4 -2 3 1
5 -5 2 0
6 5 6 1
7 -1 12 0
8 7 10 1
9 -6 9 0
Learn Python for Data Science Course to improve your technical knowledge.