使用 Scipy FindPeaks 函数滚动应用 Pandas:类型错误

我正在使用 pandas.Series.Rolling.apply 功能中的scipy函数Find_Peaks寻求帮助。我抛出 TypeError: only size-1 arrays can be convert to Python scalars in my每次尝试,我无法理解 1.) 为什么 2.) 如何正确编写


我的最终目标:从透视日期开始,找到信号中的历史峰值。


find_peaks 函数根据峰值属性识别信号内的峰值。我正在使用 Mathworks -> prominence 方法中的突出方法有用示例


该函数本身接受一个一维数组并返回一个元组(peaks:ndarray, properties:dict)。


期望的输出:


x = np.ones((12,))

x[3] = 10

x[7] = 10

x[11] = 10

x = pd.Series(x)

x.rolling(4).apply(lambda x: find_peaks(x,prominence=.2)[0])


0      []

1      []

2      []

3      [3]

4      [3]

5      [3]

6      [3]

7      [3,7]

8      [3,7]

9      [3,7]

10     [3,7]

11     [3,7]

dtype: float64

尝试/错误消息:


x.rolling(4).apply(lambda x: find_peaks(x,prominence=.2)[0])

类型错误:只有大小为 1 的数组可以转换为 Python 标量


来自SO36680402发生此错误当函数需要单个值但您传递数组时,会引发错误“仅长度为 1 的数组可以转换为 Python 标量”。


但是,SO45254174似乎与此示例相矛盾:


import numpy as np

import pandas as pd


n = 3

a = np.arange(5)

df = pd.DataFrame(a, columns=['a'])


def keep(window, windows):

    windows.append(window.copy())

    return window[-1]


windows = list()

df['a'].rolling(n).apply(keep, args=(windows,))

df = df.tail(n)

df['a_window'] = windows

它将数组/向量添加到每个滚动块,从而产生:


   a         a_window

2  2  [0.0, 1.0, 2.0]

3  3  [1.0, 2.0, 3.0]

4  4  [2.0, 3.0, 4.0]

第一次尝试:


x.rolling(4).apply(lambda x: find_peaks(x,prominence=.2)[0])

错误:类型错误:只有大小为 1 的数组可以转换为 Python 标量


第二次尝试:


def _find_peaks(array,prominence=.2):

   peaks,_ = find_peaks(array,prominence=prominence)

   return np.empty((0,0)) if peaks.shape[0]==0 else peaks


x.rolling(4).apply(_find_peaks)

类型错误:只有大小为 1 的数组可以转换为 Python 标量


关于如何写作以及为什么我会抛出错误的任何想法将不胜感激!


收到一只叮咚
浏览 243回答 2
2回答

犯罪嫌疑人X

您可以做的是使用数组代替,并使用wlen参数 infind_peaks设置窗口长度而不是使用pd.rolling:从文档:wlen :int 或 float,可选: 样本中的窗口长度,可选择将每个峰的评估区域限制为 x 的子集。峰值始终位于窗口的中间,因此给定的长度四舍五入为下一个奇数。这个参数可以加快计算因此,您可以这样做:find_peaks(x.values, prominence=0.2, wlen=4)(array([3, 7], dtype=int64), {'left_bases': array([2, 6], dtype=int64),  'prominences': array([9., 9.]),  'right_bases': array([4, 8], dtype=int64)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python