Skip to content Skip to sidebar Skip to footer

Python Dataframe Logical Operations On Multiple Columns Using Multiple If Statements

I have a big data frame with float values. I want to perform two if logical operations. My code: df = A B 0 78.2 98.2 1 54.0 58.0 2 45.0 49.0 3 20.0 10.0 # I wa

Solution 1:

It doesn't look like you need to use pd.cut for this. You can simply use np.select:

df["A_op"] = np.select([df["A"]>70, df["A"]<40],[1,3], 2)
df["B_op"] = np.select([df["B"]>80, df["B"]<45],[1,3], 2)

print (df)

      A     B  A_op  B_op
0  78.2  98.2     1     1
1  54.0  58.0     2     2
2  45.0  49.0     2     2
3  20.0  10.0     3     3

Solution 2:

After a series of trials, I found the direct answer from the select method.

My answer:

rankdf = pd.DataFrame({'Ah':[70],'Al':[40],'Bh':[80],'Bl':[45]})
hcols = ['Ah','Bh']
lcols = ['Al','Bl']

# input columns
ip_cols = ['A','B']

#create empty op columns in df
op_cols = ['A_op','B_op']
df = pd.concat([df,pd.DataFrame(columns=op_cols)])

# logic operationdf[op_cols] = np.select([df[ip_cols ]>rankdf[hcols].values, df[ip_cols]<rankdf[lcols].values],[1,3],2)

Present output:

AB  A_op  B_op
078.298.211154.058.023245.049.023320.010.033

Post a Comment for "Python Dataframe Logical Operations On Multiple Columns Using Multiple If Statements"