1

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'])]

khalilnait
  • 15
  • 3
  • 2
    Please don't post pictures. Picture's don't help. Please take a tour of [how-to-make-good-reproducible-pandas-examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – Shubham Sharma Jun 12 '20 at 12:59
  • Your first syntax seems correct but are you sure that the final outcome should be what you posted ? It seems to me that `0` is not between `8.08`and `7.2` ? – H4kim Jun 12 '20 at 13:08
  • i am sorry i removed it , this not the final outcome – khalilnait Jun 12 '20 at 13:10
  • Your first try just works fine to me then. You could also have multiplied the result by `1` instead of using `astype(int)` : `A['DM'] = 1.0 * ((A['DOWN'] <= A['Y']) & (A['Y'] <= A['UP']))` – H4kim Jun 12 '20 at 13:12

2 Answers2

0

np.where() is the way to go:

import numpy as np
A[‘DM’] = np.where(((A[‘Y’] > A[‘up’]) & (A[‘Y’] < A[‘down’])) | ((A[‘Y’] < A[‘up’]) & (A[‘Y’] > A[‘down’])), 1, 0)

That should do it. Hopefully there is no typo as I’m replying on mobile.

David Erickson
  • 16,433
  • 2
  • 19
  • 35
0

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.

Xalemon
  • 36
  • 4