在Python中调整数据序列大小的最佳方法

2024-10-03 09:19:10 发布

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

我有一个数据序列(列表),我必须调整大小。我已经为它编写了一个函数,但它非常粗糙。有没有人知道更好的方法来解决这个问题?在

预期行为:

在所有示例中,我的输入数据序列如下: 编辑:即使这个例子是线性的,你也不能指望序列是由公式构建的。在

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

当我将它从10个项目调整为5个项目时,我希望得到如下输出:

[1, 3, 5, 7, 9]或{}

现在,当您将数据序列的长度减半时,所有这些都不是很困难,但是输出序列的大小是可变的。我可以小于或大于原始序列的长度。在

当我把它从10个项目调整到19个项目时(很容易手动完成数字),我希望如下所示:

[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10]

电流函数

def sequenceResize(source, length):
    """
    Crude way of resizing a data sequence.
    Shrinking is here a lot more accurate than expanding.
    """
    sourceLen = len(source)
    out = []
    for i in range(length):
        key = int(i * (sourceLen / length))
        if key >= sourceLen:
            key = sourceLen - 1

        out.append(source[key])
    return out

结果如下:

^{pr2}$

收缩是精确的,但是扩展序列就不是那么好了。在

有没有人知道一个现有的或简单的方法来妥善处理这个问题?在


Tags: 数据项目方法key函数编辑示例source
2条回答

你可以用np.lisnpace公司公司名称:

import numpy as np

list_in = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

resize = 19

list_out = np.linspace(list_in[0], list_in[-1], num=resize)

print(np.ndarray.tolist(list_out))

输出:

^{pr2}$

与其直接确定索引,不如计算两个列表中索引之间的“步数”比率。注意,比列表中的元素少一个步骤。然后,您可以得到floorceil项,并根据当前步骤的小数部分确定最终值,得到两者之间的加权平均值(见下图)。在

def sequenceResize(source, length):
    step = float(len(source) - 1) / (length - 1)
    for i in range(length):
        key = i * step
        low = source[int(math.floor(key))]
        high = source[int(math.ceil(key))]
        ratio = key % 1
        yield (1 - ratio) * low + ratio * high

或者稍短一点,使用divmod

^{pr2}$

示例:

>>> sequence = [1, 2, 4, 8, 16]
>>> list(sequenceResize(sequence, 5))
[1, 2.0, 4.0, 8.0, 16.0]
>>> list(sequenceResize(sequence, 3))
[1, 4.0, 16.0]
>>> list(sequenceResize(sequence, 10))
[1, 1.44444, 1.88889, 2.66667, 3.55556, 4.88889, 6.66667, 8.88889, 12.44444, 16.0]
>>> list(sequenceResize(sequence, 19))
[1, 1.22222, 1.44444, 1.66667, 1.88889, 2.22222, 2.66667, 3.11111, 3.55556, 4.0, 4.88889, 5.77778, 6.66667, 7.55556, 8.88889, 10.66667, 12.44444, 14.22222, 16.0]

另一个例子作为例证。蓝色是原始值,红色是插值值。在

enter image description here

相关问题 更多 >