Checking 2 conditions between 2 columns in a dataframe

Viewed 33

I need to compare values from 2 different columns in my data frame and set the value of another column in the same data frame.

The conditions being:

If First Character of value in Column "code" = "V" and column "event_date" is not NULL
    Set Value of Label Column = 1
Else 
    Set Value of Label Column = 0

Here is my code

data1['label'] = np.where((data2['code'].str.slice(0, 1)=='V') & (data2['event_Date'].notnull), 1, 0)

This does not seem to be working.

Please help.

2 Answers

Use df.apply with axis = 1 to apply a function to your dataframe row-wise.

import pandas as pd

# create some random data
df = pd.DataFrame({'code': ['Vs', 'vx', 'Vxyz'], 'event_date': ['01-30-20', '03-01-20', None]})

# we should expect that only row 1 --> label = 1
# the code for row 2 doesn't begin with 'V' --> label = 0
# and code for row 3 has None for the date --> label = 0

def set_value(x):
    if x['code'][0] == 'V' and x['event_date'] != None:
        return 1
    else:
        return 0

# apply the function to each row of the df
df['label'] = df.apply(lambda x: set_value(x), axis = 1)

Output:

>>> df
   code event_date  label
0    Vs   01-30-20      1
1    vx   03-01-20      0
2  Vxyz       None      0

I was able to solve this like this:

data1['label'] = np.where((data2['code'].str.slice(0, 1)=='V') & (data2['event_Date'].notnull()), 1, 0)
Related