Skip to main content
 首页 » 编程设计

python之在 Pandas 中查询满足一组条件的最近对象(及时)

2025年04月02日16落叶

我正在使用 Pandas 来管理一组具有多个属性的文件:

import pandas as pd 
 
data = {'Objtype'   : ['bias', 'bias', 'flat', 'flat', 'StdStar', 'flat', 'Arc', 'Target1', 'Arc', 'Flat', 'Flat', 'Flat', 'bias', 'bias'],  
        'UT'        :  pd.date_range("11:00", "12:05", freq="5min").values, 
        'Position'  : ['P0', 'P0', 'P0', 'P0', 'P1', 'P1','P1', 'P2','P2','P2', 'P0', 'P0', 'P0', 'P0']} 
 
df   = pd.DataFrame(data=data) 

这给了我一个像这样的数据框:

    Objtype Position                  UT 
0      bias       P0 2016-07-15 11:00:00 
1      bias       P0 2016-07-15 11:05:00 
2      flat       P0 2016-07-15 11:10:00 
3      flat       P0 2016-07-15 11:15:00 
4   StdStar       P1 2016-07-15 11:20:00 
5      flat       P1 2016-07-15 11:25:00 
6       Arc       P1 2016-07-15 11:30:00 
7   Target1       P2 2016-07-15 11:35:00 
8       Arc       P2 2016-07-15 11:40:00 
9      Flat       P2 2016-07-15 11:45:00 
10     Flat       P0 2016-07-15 11:50:00 
11     Flat       P0 2016-07-15 11:55:00 
12     bias       P0 2016-07-15 12:00:00 
13     bias       P0 2016-07-15 12:05:00 

除了另一个对象之外,我还想索引满足时间条件的对象。例如:

我想要最接近 Target1 的对象,其 Objtype 是“Arc”。对于这个查询,我会得到两个候选项:6 和 8。

例如,如果我要查询最接近 Target1 的对象,其 Objtype 是 'Arc' 并且共享相同的 Position (P2) .我会得到 8。

我试图根据初始条件对数据帧进行切片,然后使用 numpy,但我正在制造一个非 pythonic 的困惑。

有什么建议吗?

请您参考如下方法:

让我们构建一个函数

def get_closest(df, idx, bool_cond, to_this): 
    others = df.loc[bool_cond, to_this] 
    target = df.loc[idx, to_this] 
    return df.ix[(others - target).abs().idxmin()] 

首先,假设当您正在寻找与我们有唯一索引的其他事物最接近的事物时。如果你不这样做,得到它。在本例中,索引为 7,因为它对应于 'Target1' 的值。接下来,构建一个代表您关心的条件的 bool 系列。

cond1 = df.Objtype == 'Arc' 
cond2 = df.Position == df.loc[7, 'Position'] 

然后我们可以这样调用我们的函数:

get_closest(df, 7, cond1, 'UT') 
 
Objtype                     Arc 
Position                     P1 
UT          2016-07-15 11:30:00 
Name: 6, dtype: object 

完美!你提到有 2 件元素同样接近,我不介意两者都送。我会把它留给你作为练习。此函数确实提供了最接近且满足条件的行。

关于:

get_closest(df, 7, cond1 & cond2, 'UT') 
 
Objtype                     Arc 
Position                     P2 
UT          2016-07-15 11:40:00 
Name: 8, dtype: object 

太棒了!这就是我们想要的。


get_closest的解释

  • df 是我们关心的数据框。
  • idx 是代表我们目标的索引。
  • bool_cond 是 True/False 系列来切片我们的 df
  • to_this 是我们用来测量距离的列名。

def get_closest(df, idx, bool_cond, to_this): 
    # filter dataframe 
    others = df.loc[bool_cond, to_this] 
    # get to_this value for target row 
    target = df.loc[idx, to_this] 
    # get index value for smallest absolute difference 
    # and use it to get the resulting row 
    return df.ix[(others - target).abs().idxmin()]