简体   繁体   English

在已排序的 pandas 数据框中查找与列表中的值最接近的值

[英]Find the closest values in a sorted pandas dataframe to values in a list

I have seen :我见过 :

How do I find the closest values in a Pandas series to an input number? 如何在 Pandas 系列中找到与输入数字最接近的值?

I have a pandas DataFrame like this :我有一个像这样的熊猫数据框:

idx编号 col1 col1 col2 col2
1 1 2 2 56 56
2 2 3 3 22 22
3 3 6 6 12 12
4 4 7 7 7 7
5 5 7.5 7.5 6 6
6 6 9 9 9 9
7 7 10.1 10.1 11 11
8 8 11 11 23 23

and an input list like this :和这样的输入列表:

[ 4, 7.6, 10] [ 4, 7.6, 10]

I want to keep the same number of rows as the list length, where the elements in df['col1'] are the closest to the elements in the list such that y output DataFrame is :我想保持与列表长度相同的行数,其中 df['col1'] 中的元素最接近列表中的元素,因此 y 输出 DataFrame 为:

idx编号 col1 col1 col2 col2
2 2 3 3 22 22
5 5 7.5 7.5 6 6
7 7 10.1 10.1 11 11

What is an efficient solution when dataframe and list get big?当数据框和列表变大时,什么是有效的解决方案?

You can use broadcasting in numpy to obtain the differences and then get the index conaininng the minimum absolute value您可以在 numpy 中使用broadcasting来获取差异,然后获取包含最小绝对值的索引

a = np.array([4,7.6,10]).reshape(1,-1) #np.array([[4,7.6,10]])
df.iloc[abs(df.col1.to_numpy()[:,None] - a).argmin(0)]

   idx  col1  col2
1    2   3.0    22
4    5   7.5     6
6    7  10.1    11

第一种方法是减法,但您是否考虑过在您提到的主题中使用分区的解决方案?

There's merge_asof for matching sorted data:有用于匹配排序数据的merge_asof

pd.merge_asof(pd.DataFrame({'key':inpt}), df, 
              right_on='col1', left_on='key',
              direction='nearest')

Output:输出:

    key  idx  col1  col2
0   4.0    2   3.0    22
1   7.6    5   7.5     6
2  10.0    7  10.1    11

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

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