简体   繁体   English

如何在 Pandas 中获得最接近的匹配值?

[英]How to get the nearest matching value in Pandas?

I have one table:我有一张桌子:

Index指数 Month_1月_1
01 01 12 12
02 02 09 09

A user input for month is taken.获取月份的用户输入。 The user gives input 11.用户输入 11。

How we can match the user input month to the nearest month?我们如何将用户输入的月份与最近的月份相匹配?

In this case the output should be:在这种情况下,output 应该是:

Index指数 Month_1月_1
01 01 12 12

Logic: The month given by user is 11. Nearby month present in the table is 12. So the output is 12 (in table format shown above).逻辑:用户给出的月份是 11。表中存在的邻近月份是 12。所以 output 是 12(如上所示的表格格式)。

Subtract values, get absolute values and then get position of minimal value, last select rows, there is double [] for one row DataFrame:减去值,得到绝对值,然后得到最小值的 position,最后 select 行,一行 DataFrame 有双[]

a = 11
df = df.iloc[[df['Month_1'].sub(a).abs().argmin()]]
print (df)
  Index  Month_1
0    01       12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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