如何修复Savitzky-Golay滤波时的AttributeError: 'list'无'shape'属性错误?
解决sgolay2d调用时的AttributeError: 'list' object has no attribute 'shape'问题
这个错误原因很明确:sgolay2d函数要求输入是numpy数组,而你传入的是Python原生的list类型。List没有shape属性,而函数内部需要通过z.shape来获取数据的维度信息,所以触发了这个报错。
下面是具体的解决步骤和代码示例:
1. 把list转换为numpy数组
numpy数组是科学计算函数(包括sgolay2d)的标准输入格式,它自带shape属性,能满足函数的维度检查需求。
2. 确保数据是二维格式
sgolay2d是二维Savitzky-Golay平滑滤波函数,所以需要输入二维数据。如果你的方波是一维序列(比如[0,0,1,1,0,0...]),还需要把一维数组转成二维结构(比如列向量或行向量)。
修改后的代码示例
import numpy as np from scipy.signal import sgolay2d # 你的原始方波list数据 total = [0, 0, 1, 1, 0, 0, 1, 1, 0, 0] # 步骤1:将list转为numpy数组 total_np = np.array(total) # 步骤2:将一维数组转为二维(以列向量为例,shape变为(n, 1)) total_2d = total_np.reshape(-1, 1) # 如果你需要行向量,可以用total_np.reshape(1, -1) # 调用sgolay2d执行平滑 # 注意window_size必须是奇数,order不能超过window_size-1 smoothed_data = sgolay2d(total_2d, window_size=3, order=1) # 如果需要将结果转回list,可以这么做 smoothed_list = smoothed_data.flatten().tolist()
特殊情况:如果你的数据已经是二维list
比如你的total是类似[[0,1,0], [1,0,1], [0,1,0]]的二维结构,只需要转成numpy数组即可,不需要reshape:
total_np = np.array(total) smoothed_data = sgolay2d(total_np, window_size=3, order=1)
总结一下,核心就是把Python原生list转换为numpy数组,并确保数据维度符合sgolay2d的二维要求,这样就能解决这个属性错误了。
内容的提问来源于stack exchange,提问作者Anwar Elhadad
相关产品推荐
相关产品推荐

