[英]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: output 应该是:
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逻辑:在 Month_1 和 Month_2 附近的付费字段中添加“是”
You can subtract columns, get absolute values and compare if equal or less like threshold, eg 2
and then set values in numpy.where
:您可以减去列,获取绝对值并比较是否等于或小于阈值,例如
2
,然后在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.