Python Forum
applying and(&) ,or(|) in conditions does not result output correctly as expected
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
applying and(&) ,or(|) in conditions does not result output correctly as expected
#1
I have data as below(sample only, data will have all combinations of below values). I have to create new column based conditions applied on 3 columns.
Output:
A B C Normal Normal Normal High High High High High Low Low Low High Normal Normal Low Normal Normal High Normal High High No Test No Test High No Test No Test Low No Test No Test No Test No Test High High
def flag_df(df):

    if df[(df['A']=='Normal') & (df['B']=='Normal') & (df['C']=='Normal')]:
        return 'Normal'
    elif df[(df['A']=='High']) & (df['B']=='High') & (df['B']=='Low')]:
        return 'OH'
    elif df[(df['A']=='Normal']) & (df['B']=='Normal') & (df['C']=='Low')]:
        return 'SHPE'
    elif df[(df['A']=='Normal']) & (df['B']=='Normal') & (df['C']=='High')]:
        return 'SHPO'
    elif df[(df['A']=='No Test']) & (df['B']=='No Test') & (df['C']=='No Test')]:
        return 'No Test'
    elif df[(df['A']=='No Test']) | (df['B']=='No Test') & (df['C']=='High')]:
        return 'SHPO'   
df['D'] = df.apply(flag_df, axis = 1)  
The results are coming correctly for below
#expect is col-A or Col-B has "High" but Col C has "High" it should label Col-D as 'SHPO'
elif df[(df['A']=='No Test']) | (df['B']=='High') & (df['C']=='High')]:
        return 'SHPO'   
#expect is col-A AND Col-B has "no Test" but Col C has "High" it should label Col-D as 'SHPO'
elif df[(df['A']=='No Test']) & (df['B']=='No Test') | (df['C']=='High')]:
        return 'SHPO'  
How to work with | or & operators on 3 or more column conditions, is there a better approach to write a function? Appreciate your help, Thank you!!!
Reply
#2
& and | are bitwise operators for use with integers, typically integers used as bit flags. 'and' and 'or' are logical operators intended to be used with truth values. Furthermore, and/& is evaluated before or/|, due to order of operations. If you are doing multiple tests they may not be occurring in the order you expect.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thank you very much for quick response. I tried to use 'and' 'or' as the column has string but not sure why it did not work. It worked well with bitwise operators & |

I was getting this error when I used "and" , which I just tried again after your response, what you do think the issue here ? the dtype for these colms was 'object' and I converted to 'string' . Please suggest

Output:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-714-eeb5bb60c70f> in <module> ----> 1 df111=df[(df['A']=='High') and (df['B']=='High') and (df['C']=='Normal')] 2 df111.head(1000) C:\BhargaviM\MyAnaconda\lib\site-packages\pandas\core\generic.py in __nonzero__(self) 1574 raise ValueError("The truth value of a {0} is ambiguous. " 1575 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." -> 1576 .format(self.__class__.__name__)) 1577 1578 __bool__ = __nonzero__ ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Reply
#4
I am sorry I realized that cols A, B and C are still in object even when tried to convert the string df['A'].astype('str)

I can open a new one though, but I would like to check if the solution above works before i close this post. Thanks
Reply
#5
The error is pretty clear. A Series does not have an inherent truth value like other Python objects, because it's not clear how that value would be calculated. You need to use one of the methods listed to convert to a truth value, depending how how you want it calculated.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Facing problem with Pycharm - Not getting the expected output amortal03 1 820 Sep-09-2022, 05:44 PM
Last Post: Yoriz
  gspread - applying ValueRenderOption to a range of cells dwassner 0 1,672 Jan-12-2022, 03:05 PM
Last Post: dwassner
  Applying function mapypy 1 2,236 Mar-11-2021, 09:49 PM
Last Post: nilamo
  Applying Moving Averages formula to a number lynnette1983 1 1,998 Sep-29-2020, 10:21 AM
Last Post: scidam
  Hi, I need help with defining user's input and applying it to code. jlmorenoc 2 2,236 Jun-24-2020, 02:10 PM
Last Post: pyzyx3qwerty
  print result in OUTPUT not in TERMINAL picasso 1 2,015 Apr-15-2020, 03:51 PM
Last Post: deanhystad
  Help with applying this instrument monitoring code to multiple inputs. Kid_Meier 1 2,043 Mar-04-2020, 12:01 PM
Last Post: Kid_Meier
  Applying row height to all rows including and after row 7 curranjohn46 2 6,498 Oct-14-2019, 03:10 PM
Last Post: curranjohn46
  Post JSON from python to PHP don't give expected result pgagnebin 1 3,689 Sep-04-2019, 10:29 PM
Last Post: micseydel
  Unexpected expected type error result MartinMaker 1 2,017 Feb-16-2019, 05:02 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020