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 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽4 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战5 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋10 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构