用pandas查询最接近的对象(按时间)满足一系列条件

2024-09-29 23:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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的混乱。你知道吗

有什么建议吗?你知道吗


Tags: 文件对象datapositionpdp2flatp1
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:17

让我们建立一个函数

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'的对应值。接下来,构建一个表示所关心的条件的布尔序列。你知道吗

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

太好了!你提到有两个项目一样接近,我不想交付两个。我把它作为练习留给你。此函数确实传递了最接近并满足条件的行。你知道吗

关于:

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_condTrue/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()]

相关问题 更多 >

    热门问题