简体   繁体   中英

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

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

You can subtract columns, get absolute values and compare if equal or less like threshold, eg 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     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM