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]]]
'''
相关推荐
哥本哈士奇(aspnetx)1 天前
Streamlit + LangChain 1.0 简单实现智能问答前后端
python·大模型
我一定会有钱1 天前
斐波纳契数列、end关键字
python
小鸡吃米…1 天前
Python 列表
开发语言·python
星依网络1 天前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
清风一徐1 天前
禅道从18.3升级到21.7.6版本
笔记
Jack___Xue1 天前
LangChain实战快速入门笔记(六)--LangChain使用之Agent
笔记·langchain·unix
大佐不会说日语~1 天前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
零度@1 天前
SQL 调优全解:从 20 秒到 200 ms 的 6 步实战笔记(附脚本)
数据库·笔记·sql
2501_921649491 天前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
qq_448011161 天前
python HTTP请求同时返回为JSON的异常处理
python·http·json