Python使用scipy.signal.argrelextrema查找离散序列极值点

白榆
白榆
发布时间:2026-10-13| 6人浏览过
原创

本文介绍利用Python中scipy.signal库的argrelextrema函数来高效查找离散序列中的极值点。通过示例代码展示如何定位局部极大值与极小值,并指出该函数在遇到连续相同数值时的识别局限,帮助用户在实际数据处理中合理应用此方法。

使用scipy.signal查找极值点

在Python中,可以使用scipy.signal模块提供的argrelextrema函数来便捷地查找离散序列中的极值点。该方法API简洁,易于实现。


import numpy as np 
import pylab as pl
import matplotlib.pyplot as plt
import scipy.signal as signal
x=np.array([
  0, 6, 25, 20, 15, 8, 15, 6, 0, 6, 0, -5, -15, -3, 4, 10, 8, 13, 8, 10, 3,
  1, 20, 7, 3, 0 ])
plt.figure(figsize=(16,4))
plt.plot(np.arange(len(x)),x)
print x[signal.argrelextrema(x, np.greater)]
print signal.argrelextrema(x, np.greater)

plt.plot(signal.argrelextrema(x,np.greater)[0],x[signal.argrelextrema(x, np.greater)],'o')
plt.plot(signal.argrelextrema(-x,np.greater)[0],x[signal.argrelextrema(-x, np.greater)],'+')
# plt.plot(peakutils.index(-x),x[peakutils.index(-x)],'*')
plt.show()

[25 15 6 10 13 10 20]
(array([ 2, 6, 9, 15, 17, 19, 22]),)

函数局限性与注意事项

需要注意的是,当极值点附近存在左右相邻且数值相同的点时,该函数可能无法正确识别极值。不过,在实际应用场景中,这种情况较为罕见,因此通常可以忽略这一限制。


x=np.array([
  0, 15, 15, 15, 15, 8, 15, 6, 0, 6, 0, -5, -15, -3, 4, 10, 8, 13, 8, 10, 3,
  1, 20, 7, 3, 0 ])
plt.figure(figsize=(16,4))
plt.plot(np.arange(len(x)),x)
print x[signal.argrelextrema(x, np.greater)]
print signal.argrelextrema(x, np.greater)

plt.plot(signal.argrelextrema(x,np.greater)[0],x[signal.argrelextrema(x, np.greater)],'o')
plt.plot(signal.argrelextrema(x,np.less)[0],x[signal.argrelextrema(x, np.less)],'+')
plt.show()

[15 6 10 13 10 20]
(array([ 6, 9, 15, 17, 19, 22]),)

以上内容分享了利用Python查找离散序列极值点的方法,希望能为读者提供有价值的参考。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。