0

I am attempting to write the following logic in python:

if column A is '123' and column B is '456', then column c = 0

I've tried the following function, but returns an error:

 def testfunc(df):
     if df['columna'] == 123:
         if df['columnb'] ==456:
             df['columnc']=0

 return df
 testfunc()

error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What am i doing wrong?

1
  • In input DataFrame exist column columnc ? Commented Nov 29, 2018 at 6:29

1 Answer 1

1

Use numpy.where and chain conditions with & for bitwise AND:

Solution if exist column columnc:

def testfunc(df):
    m1 = df['columna'] == 123
    m2 = df['columnb'] == 456
    df['columnc']= np.where(m1 & m2, 0, df['columnc'])
    return df

If not exist is necessary define both values like 0 and 10:

def testfunc(df):
    m1 = df['columna'] == 123
    m2 = df['columnb'] == 456
    df['columnc']= np.where(m1 & m2, 0, 10)
    return df

Sample:

df = pd.DataFrame({
         'columna':[123,123,4,5],
         'columnb':[456,8,456,4],
         'columnc':[1,3,5,7],

})
print (df)
   columna  columnb  columnc
0      123      456        1
1      123        8        3
2        4      456        5
3        5        4        7

def testfunc(df):
    m1 = df['columna'] == 123
    m2 = df['columnb'] == 456
    df['columnc']= np.where(m1 & m2, 0, df['columnc'])
    return df

df1 = testfunc(df)
print (df1)
   columna  columnb  columnc
0      123      456        0
1      123        8        3
2        4      456        5
3        5        4        7
def testfunc(df):
    m1 = df['columna'] == 123
    m2 = df['columnb'] == 456
    df['columnc']= np.where(m1 & m2, 0, 10)
    return df

df1 = testfunc(df)
print (df1)
   columna  columnb  columnc
0      123      456        0
1      123        8       10
2        4      456       10
3        5        4       10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.