Compare two columns with conditions

Question:

I have two column, say A and B. I want to compare if A exceeds column B more than 500, add 1 in new column, else 0.

My sample df:

A       B
13450   12000
10000   12000
5240    5000
5000    5000
60000   70000

Expected result:

A       B        C
13450   12000    1
10000   12000    0
5600    5000     1
5000    5000     0
60000   70000    0

Using the ‘Greater Than’ I can compare two column, but I can’t figure out how to do this for a condition A column exceeds B more than 500.

Any help would be much appreciated!

Asked By: Mika

||

Answers:

Try something like:

df['c']  = np.where((( df['a']-df['b']) > 500), 1,0) 
Answered By: Renaud

It is a very simple logic just some basic comparing operation to be performed

import pandas as pd
df = pd.read_excel('pathoffile.xlsm') 
a = df['col1'].tolist()
b = df['col2'].tolist()
c=[]
for i in len(a):
  if a[i]-b[i]<500:
    c.append(0)
  else:
    c.append(1)
print(c)

Now write the c value into the xls file in third column into the xls file and you will get the desired result.

Answered By: raza sikander
>>> df['C'] = (df.A - df.B).ge(500).astype(int)
>>> df
       A      B  C
0  13450  12000  1
1  10000  12000  0
2   5240   5000  0
3   5000   5000  0
4  60000  70000  0

You can find the difference of the column using the - operator, then check condition is greater than 500 using pandas.Series.ge method and finally convert it into int type by pandas.Series.astype

Answered By: Dishin H Goyani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.