gpt4 book ai didi

在 2D numpy 数组中加入近端段的 Pythonic 方法?

转载 作者:行者123 更新时间:2023-12-01 06:28:53 25 4
gpt4 key购买 nike

我有一个二维 numpy 数组,它将分段时间段表示为开始/结束时间。我设计了一种在片段接近时(小于某个最小间隙长度)连接片段的方法:

def join_proximal_segments(original_segments, min_gap):

begins = np.array([original_segments.T[0, 0]])
ends = np.array([])

for i in np.arange(len(original_segments)-1):

if((original_segments.T[0, i+1] - original_segments.T[1, i]) > min_gap):

begins = np.append(begins, original_segments.T[1, i])
ends = np.append(ends, original_segments.T[0, i+1])

ends = np.append(ends, original_segments.T[1, -1])

joined_segments = np.array([begins, ends]).T

return joined_segments

看起来很不优雅。有没有更直接的方法使用 numpy 来解决这个问题?

编辑:示例数组

detections = np.array([[2, 60],[62, 78],[97, 105],[255, 340],[343, 347]])

最佳答案

我不确定我是否完全理解您的问题,但我希望这个示例足以帮助您找出问题的向量化:

import numpy as np

min_gap = 10
original_segments = np.array([[ 2, 60],
[ 62, 78],
[ 97, 105],
[255, 340],
[343, 347]])


def join_proximal_segments(original_segments, min_gap):
diff = original_segments[1:, 0] - original_segments[:-1, 1]
diff_bool = diff > min_gap

joined_segments = np.empty((sum(diff_bool)+1, 2),
dtype=original_segments.dtype)
# beginnings
joined_segments[0, 0] = original_segments[0, 0]
joined_segments[1:, 0] = original_segments[:-1, 1][diff_bool]
# ends
joined_segments[:-1, 1] = original_segments[1:, 0][diff_bool]
joined_segments[-1, 1] = original_segments[-1, 1]

return joined_segments


print(join_proximal_segments(original_segments, min_gap))
# [[ 2 97]
# [ 78 255]
# [105 347]]

关于在 2D numpy 数组中加入近端段的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59995473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com