How to apply function to two columns of Pandas dataframe and two if fucntion

Viewed 43

I want to create a class based on systolic blood pressure and diastolic blood pressure. i have df which has columns of Systolic and Diastolic. And I define a function :

f = lambda x, y : my_function_expression.

Now I want to apply the f to df's two columns Systolic and Diastolic to to create a class on the new column Blood_Pressure, somewhat like :

df['Blood_Pressure'] = df['Systolic', 'Diastolic'].apply(lambda x, y : 0 if x >=90 and x <=120 and y >=60 and y <=80 else 1)

How to do? is there any other way?

examples of the results I want :

enter image description here

1 Answers

In general, when working with dataframes, you should avoid apply and try to think of your data in terms of features (columns). Pandas does provide many vectorized operations while apply is not.

In your case, you can do between:

df['Class'] = (df['Systolic'].between(90,120) & 
               df['Distolic'].between(60,80)
              ).astype(int)
Related