numpy:如何平滑数组列中的x,y,z值?

iovurdzv  于 2023-05-17  发布在  其他
关注(0)|答案(2)|浏览(116)

我有加速度计数据-为了简单起见,只是加速度-加载到一个numpy数组中,就像这样(玩具数据;列为x,y,z):

import numpy as np
import pandas as pd
from scipy.interpolate import make_interp_spline, BSpline
idx = [1,2,3,4]
idx = np.array(idx,dtype=int)
accel = [[-0.7437,0.1118,-0.5367],
         [-0.5471,0.0062,-0.6338],
         [-0.7437,0.1216,-0.5255],
         [-0.4437,0.3216,-0.3255],
]
accel = np.array(accel,dtype=float)

我想平滑这些值。我已经找到了一个here的例子,说明如何使用bspline来实现。麻烦的是这个例子使用了一个1d数组。我还没有足够好的Python来弄清楚如何在2D数组中重现这一点。我可以为x提取一个列切片,并像这样平滑它:

x = accel[:,0]
idxnew = np.linspace(idx.min(), idx.max(), 200) 
spl = make_interp_spline(idx, x, k=3)
x_smooth = spl(idxnew)

但我不确定如何将其写回新的更长数组的第一列。我尽力了

accel_sm = []
accel_sm = np.array(idx,dtype=float)
np.hstack(accel_sm,x_smooth)

但这会抛出“TypeError:应为类似字节的对象,而不是str”。我有点卡住了。有人能给我指个方向吗?

ukdjmx9f

ukdjmx9f1#

我猜问题是x_smooth被识别为一个向量-但你需要将其视为一个具有一列的矩阵-> use reshape。

x_smooth = x_smooth.reshape(-1,1)
for i in range(1,accel.shape[1]):
    x = accel[:, i]
    idxnew = np.linspace(idx.min(), idx.max(), 200)
    spl = make_interp_spline(idx, x, k=3)
    x_smooth = np.concatenate([x_smooth,spl(idxnew).reshape(-1,1)],axis=1)```

You can detect the problem via viewing x_smooth.shape which gives (200,) but you need (200,1)
tyg4sfes

tyg4sfes2#

一个朋友能够像这样工作(代码添加到OP中的第一个块):

ts_length = 200
accel_sm = np.zeros([ts_length,3])
idxnew = np.linspace(idx.min(), idx.max(), ts_length) 
for i in range (0,3):
         c = accel[:,i]
         spl = make_interp_spline(idx, c, k=3)
         c_smooth = spl(idxnew)
         accel_sm[:, i] = c_smooth
print(accel_sm)

我实际上已经尝试过这种方法-将c_smooth分配给accell_sm的一个切片-但它不起作用,因为我没有先用零填充目标。我通常在Perl的代码中不需要预先填充数组,但你在Python中这样做,我已经学会了。

相关问题