gpt4 book ai didi

python - 如何使用 numpy 在列表中的值对之间进行插值

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

我有这样的列表:

x_data = [3, 5, 7, 8, 5, 2]
y_data = [15, 20, 22, 23, 21, 14]

我想在列表中的项目对之间进行插值,这样列表的长度不再是 6,而是长度为 n,列表中每对项目之间的间距值相等。我当前的方法是使用列表理解来遍历列表中的对,并使用 np.extend 包含结果的空列表。有没有更好的现成函数可以做到这一点?

我目前的方法:

import numpy as np

x_data = [3, 5, 7, 8, 5, 2]
y_data = [15, 20, 22, 23, 21, 14]
result_x = []
result_y = []
[result_x.extend(np.linspace(first, second, 5)) for first, second, in zip(x_data, x_data[1:])]
[result_y.extend(np.linspace(first, second, 5)) for first, second, in zip(y_data, y_data[1:])]
print(result_x, '\n'*2, result_y)

Out: [3.0, 3.5, 4.0, 4.5, 5.0, 5.0, 5.5, 6.0, 6.5, 7.0, 7.0, 7.25, 7.5, 7.75, 8.0, 8.0, 7.25, 6.5, 5.75, 5.0, 5.0, 4.25, 3.5, 2.75, 2.0]



[15.0, 16.25, 17.5, 18.75, 20.0, 20.0, 20.5, 21.0, 21.5, 22.0, 22.0, 22.25, 22.5, 22.75, 23.0, 23.0, 22.5, 22.0, 21.5, 21.0, 21.0, 19.25, 17.5, 15.75, 14.0]

最佳答案

我认为这个函数使用 np.interp 可以满足您的需求:

import numpy as np

def interpolate_vector(data, factor):
n = len(data)
# X interpolation points. For factor=4, it is [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, ...]
x = np.linspace(0, n - 1, (n - 1) * factor + 1)
# Alternatively:
# x = np.arange((n - 1) * factor + 1) / factor
# X data points: [0, 1, 2, ...]
xp = np.arange(n)
# Interpolate
return np.interp(x, xp, np.asarray(data))

示例:

x_data = [3, 5, 7, 8, 5, 2]
y_data = [15, 20, 22, 23, 21, 14]

print(interpolate_vector(x_data, 4))
# [3. 3.5 4. 4.5 5. 5.5 6. 6.5 7. 7.25 7.5 7.75 8. 7.25
# 6.5 5.75 5. 4.25 3.5 2.75 2. ]
print(interpolate_vector(y_data, 4))
# [15. 16.25 17.5 18.75 20. 20.5 21. 21.5 22. 22.25 22.5 22.75
# 23. 22.5 22. 21.5 21. 19.25 17.5 15.75 14. ]

关于python - 如何使用 numpy 在列表中的值对之间进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303203/

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