Phoenix
Phoenix

Reputation: 73

Assign value in each row of a pandas dataframe based on condition

I have written the code shown below:

for ind in df.index:
  X=df['POG_X'][ind]
  Y=df['POG_Y'][ind]
  if -960<X<0 and -540<Y<0:
     df.loc[df.index[ind],'Is_ROI']='TRUE'
  else:
     df.loc[df.index[ind],'Is_ROI']='FALSE'

So, basically what I am trying to achieve is to assign a 'TRUE' or 'FALSE' value on the 'Is_ROI' column of a pandas df. I can read the X,Y values of each row, but the assignment of TRUE or FALSE, doesn't work as intended. I get either TRUE or FALSE values in the entire 'Is_ROI' column, regardless of the if statement. What I'm missing here?

Upvotes: 0

Views: 766

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24322

Directly store your conditions in a column:

df['Is_ROI']=(df['POG_X'].between(0,-960,inclusive='neither')) & (df['POG_X'].between(0,-540,inclusive='neither'))

OR

without between():

df['Is_ROI']=(df['POG_X'].gt(-960) & df['POG_X'].lt(0)) & (df['POG_Y'].gt(-540) & df['POG_X'].lt(0))

Note:

  • If you don't need boolean True/False and you need string True/False then just chain astype(str) at the end
  • If you don't want to include boundaries in comparision then pass inclusive='neither' in between() method and if you want to include those boundries then remove inclusive parameter

Upvotes: 1

Related Questions