首页 > 编程问答 >如何查找给定值两侧都有值的行?

如何查找给定值两侧都有值的行?

时间:2024-07-26 07:29:41浏览次数:2  
标签:python pandas search interpolation

Python,Pandas,我有一个包含日期时间和值的数据帧。

# Create an empty DataFrame with 'timestamp' and 'value' columns
df = pd.DataFrame(columns=['timestamp', 'value'])
df.set_index('timestamp', inplace=True)

我随着时间的推移将数据附加到该帧。

在某些时候,我想找到时间戳处的值。如果它已经在 df 中,那就太好了,很容易找到。

但是,如果我要查找的时间在两个现有值之间,我如何才能快速找到它,并在这两个包围值之间进行插值? ChatGPT 通过无效的比较引导我进行了一场快乐的追逐。

这是我迄今为止尝试过的,但不起作用:

                # Check if the target timestamp exists in the DataFrame
                timestamps = df.index
                if target_timestamp in timestamps:
                    # Exact match found
                    return df.loc[target_timestamp, 'value']
                else:
                    # Use searchsorted to find the insertion point
                    pos = timestamps.searchsorted(target_timestamp)

                    if pos == 0 or pos == len(timestamps) - 1:
                        raise ValueError("Target timestamp is out of bounds for interpolation")

                    if target_timestamp > timestamps[pos]:
                        previous_timestamp = timestamps[pos]
                        next_timestamp = timestamps[pos + 1]
                    else:
                        previous_timestamp = timestamps[pos - 1]
                        next_timestamp = timestamps[pos]

                    # Interpolating the value
                    previous_value = df.loc[previous_timestamp, 'value']
                    next_value = df.loc[next_timestamp, 'value']

                    # Linear interpolation formula
                    interpolated_value = previous_value + (next_value - previous_value) * \
                                        (target_timestamp - previous_timestamp) / (next_timestamp - previous_timestamp)

                    return interpolated_value


你几乎要成功了!你的代码中的问题在于你确定 previous_timestamp next_timestamp 的方式。 searchsorted 返回插入点,它可能与你的比较预期不符。

以下是修复方法:

import pandas as pd

def interpolate_value(df, target_timestamp):
    """
    查找给定时间戳处的值,如果它落在现有时间戳之间,则进行插值。

    Args:
        df (pd.DataFrame): 索引为时间戳的 DataFrame,带有一列“value”。
        target_timestamp (pd.Timestamp): 要查找值的目标时间戳。

    Returns:
        float: 插值或检索到的值。

    Raises:
        ValueError: 如果目标时间戳超出了插值范围(第一个或最后一个时间戳之外)。
    """

    # 检查目标时间戳是否存在于 DataFrame 中
    timestamps = df.index
    if target_timestamp in timestamps:
        # 找到完全匹配项
        return df.loc[target_timestamp, 'value']
    else:
        # 使用 searchsorted 查找插入点
        pos = timestamps.searchsorted(target_timestamp)

        # 如果目标时间戳超出边界,则引发错误
        if pos == 0 or pos == len(timestamps):
            raise ValueError("目标时间戳超出插值范围")

        # 获取前一个和下一个时间戳和值
        previous_timestamp = timestamps[pos - 1]
        next_timestamp = timestamps[pos]
        previous_value = df.loc[previous_timestamp, 'value']
        next_value = df.loc[next_timestamp, 'value']

        # 使用线性插值公式进行插值
        interpolated_value = previous_value + (next_value - previous_value) * \
                                    (target_timestamp - previous_timestamp) / (next_timestamp - previous_timestamp)

        return interpolated_value

更改如下:

  1. 删除了有问题的 if 语句。 在调用 searchsorted 后,你已经知道 target_timestamp 位于 pos - 1 pos 之间的某个位置。不需要其他条件。
  2. 简化了前一个和下一个时间戳的选择。 previous_timestamp 始终是 timestamps[pos - 1] next_timestamp 始终是 timestamps[pos]

此代码现在应该可以正确插值你数据帧中两个现有时间戳之间的时间戳的值。

标签:python,pandas,search,interpolation
From: 78795641

相关文章