How to check the nearest matching value between two fields in same table and add data to the third field using Pandas?

Question:

I have one table:

Index Month_1 Month_2 Paid
01 12 10
02 09 03
03 02 04
04 01 08

The output should be:

Index Month_1 Month_2 Paid
01 12 10 Yes
02 09 03
03 02 04 Yes
04 01 08

Logic: Add ‘Yes’ to the Paid field whose Month_1 and Month_2 are nearby

Asked By: Sagnik Chakraborty

||

Answers:

You can subtract columns, get absolute values and compare if equal or less like threshold, e.g. 2 and then set values in numpy.where:

df['Paid'] = np.where(df['Month_1'].sub(df['Month_2']).abs().le(2), 'Yes','')
print (df)
  Index  Month_1  Month_2 Paid
0    01       12       10  Yes
1    02        9        3     
2    03        2        4  Yes
3    04        1        8     
Answered By: jezrael
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.