Python 数据帧列上的Savgol过滤器

Python 数据帧列上的Savgol过滤器,python,pandas,scipy,Python,Pandas,Scipy,我正在尝试应用SciPy的savgol过滤器来平滑我的数据。通过分别选择每一列,定义一个新的y值并绘制它,我成功地应用了过滤器。但是,我希望在数据帧中以更有效的方式应用该函数 y0 = alldata_raw.iloc[:,0] w0 = savgol_filter(y0, 41, 1) 我的第一个想法是创建一个空数组,编写一个for循环,将函数应用于每个列,将其附加到数组中,最后连接数组。但是,我得到一个错误“TypeError:无法连接类型为“”的对象”;只有pd.Series、pd.Da

我正在尝试应用SciPy的savgol过滤器来平滑我的数据。通过分别选择每一列,定义一个新的y值并绘制它,我成功地应用了过滤器。但是,我希望在数据帧中以更有效的方式应用该函数

y0 = alldata_raw.iloc[:,0]
w0 = savgol_filter(y0, 41, 1)
我的第一个想法是创建一个空数组,编写一个for循环,将函数应用于每个列,将其附加到数组中,最后连接数组。但是,我得到一个错误“TypeError:无法连接类型为“”的对象”;只有pd.Series、pd.DataFrame和pd.Panel(已弃用)OBJ是有效的'

smoothed_array = []
for key,values in alldata_raw.iteritems():
    y = savgol_filter(values, 41, 1)
    smoothed_array.append(y)

alldata_smoothed = pd.concat(smoothed_array, axis=1)
相反,我尝试使用pd.apply()函数,但是我遇到了一些问题。我收到一条错误消息:“TypeError:预期x和y具有相同的长度”

alldata_smoothed = alldata_raw.apply(savgol_filter(alldata_raw, 41, 1), axis=1)
print(alldata_smoothed)

我对python非常陌生,因此对于如何使每种方法工作以及哪种方法更可取,我将不胜感激

为了使用过滤器,首先创建一个函数,该函数接受一个参数-列数据。然后,您可以将其应用于dataframe列,如下所示:

from scipy.signal import savgol_filter
def my_filter(x):
    return savgol_filter(x, 41, 1)
alldata_smoothed = alldata_raw.apply(my_filter)
您还可以使用
lambda
功能:

alldata_smoothed = alldata_raw.apply(lambda x: savgol_filter(x,41,1))
apply
中的
axis=1
被指定用于将函数应用于数据帧行。您需要的是默认选项
axis=0
,这意味着将其应用于列

这很一般,但是for
savgol_过滤器
告诉我它也接受一个
axis
参数。因此,在这种特定情况下,您可以立即将过滤器应用于整个数据帧。这可能会更有效,但我没有选中=)

alldata_smoothed = pd.DataFrame(savgol_filter(alldata_raw, 41, 1, axis=0),
                                columns=alldata_raw.columns,
                                index=alldata_raw.index)