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]]]
'''
相关推荐
孟健4 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞6 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽8 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程13 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪13 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook13 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python