python 笔记:将不同长度2D矩阵线性插值至相同长度(scipy.interpolate)

1 问题描述

我现在有三个2D矩阵,每一行是两个元素,代表经纬度;不同矩阵的行数不同

现在希望通过线性插补,使得每个2D矩阵行数相同

python 复制代码
pth_lst=[[[1,2],
          [1,3],
          [3,4]],
         [[3,4],
          [5,6],
          [7,8],
          [9,10],
          [11,12],
          [13,14],
          [15,16]],
         [[2,4],
          [5,8]]]     

2 解决方法

2.1 导入库

python 复制代码
import numpy as np
from scipy.interpolate import interp1d

2.2 计算各个2D矩阵需要插补到的行数

python 复制代码
max_len=0
for i in pth_lst:
    max_len=max(max_len,len(i))
max_len
#7

2.3 进行插补

python 复制代码
inter_lst=[]
#结果列表

for i in pth_lst:
    tmp=np.array(i)
    current_l=tmp.shape[0]

    new_index=np.linspace(0,current_l-1,max_len)
    #目标自变量坐标(首末位置和原来的2D矩阵一样,间隔不再是1)

    interpolate_path=interp1d(np.arange(current_l),i,axis=0)
    #对当前2D矩阵进行线性插补

    inter_lst.append(interpolate_path(new_index).tolist())
inter_lst
'''
[[[1.0, 2.0],
  [1.0, 2.3333333333333335],
  [1.0, 2.6666666666666665],
  [1.0, 3.0],
  [1.6666666666666665, 3.333333333333333],
  [2.333333333333333, 3.6666666666666665],
  [3.0, 4.0]],

 [[3.0, 4.0],
  [5.0, 6.0],
  [7.0, 8.0],
  [9.0, 10.0],
  [11.0, 12.0],
  [13.0, 14.0],
  [15.0, 16.0]],

 [[2.0, 4.0],
  [2.5, 4.666666666666667],
  [3.0, 5.333333333333333],
  [3.5, 6.0],
  [4.0, 6.666666666666666],
  [4.5, 7.333333333333333],
  [5.0, 8.0]]]
'''
相关推荐
ZhengEnCi6 分钟前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风6 小时前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风6 小时前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly20 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling1 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
齐生12 天前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
helloweilei2 天前
python 抽象基类
python