Search code examples
pythonpandasrangebetweendummy-variable

Creating new variable that equals to 1 if the existing variable lies between two values in dataframe


This my dataframe.

enter image description here

I would like to create a new varaible that equals to one if my 'Y' variable is between two values in my dataframe above (UP, DOWN).

I've tried many codes however, no satisfying results. These are the codes i've tried;

first one : A['DM'] = ((A.Y >A['UP']) & (A.Y <A['DOWN'])).astype(int)

second one :A['DM']=1 if [(A['Y'] > A['DOWN']) & (A['Y'] < A['UP'])]


Solution

  • Try like that:

    import pandas as pd
    import numpy as np
    
    A["DM"]=np.where((A.Y>A.up) & (A.Y<A.down),1,0)
    

    you need something like np.where to logical compare 2 array like objects - otherwise you would need to do that element wise.