python做数字分析,如何找到波峰波谷?
伊谢尔伦
伊谢尔伦 2017-04-17 17:54:21
0
1
1449

数字呈现不规律的波动形状,而且值变化也不一定是只朝一个方向,会有反复。请问如何能找出值排名前5的波峰和波谷的大小和位置。有计算相关的函数吗?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
左手右手慢动作

You can try using the heapq module.

import heapq

numbers = [1, 3, 5, 2, 4, 1.1, 3.5, 4.8, 0.5, 2.4, -1.5]

# 输出元祖第一个元素是index,第二元素是比较的数值
print(heapq.nsmallest(5, enumerate(numbers), key=lambda x: x[1]))
# [(10, -1.5), (8, 0.5), (0, 1), (5, 1.1), (3, 2)]

print(heapq.nlargest(5, enumerate(numbers), key=lambda x: x[1]))
# [(2, 5), (7, 4.8), (4, 4), (6, 3.5), (1, 3)]

When the number of elements to be found is relatively small, functions nlargest()nsmallest() 是很合适的。 如果你仅仅想查找唯一的最小或最大(N=1)的元素的话,那么使用min()max()函数会更快些。 类似的,如果N的大小和集合大小接近的时候,通常先排序这个集合然后再使用切片操作会更快点 (sorted(items)[:N] 或者是 sorted(items)[-N:] )。 需要在正确场合使用函数nlargest()nsmallest() can take advantage of them (if N is close to the size of the set, it will be better to use sorting operations).


nums = [1,2,3,2,4,5,4,3,2,1,8,9,10,11,10,9,8]
peaks = []
troughs = []
for idx in range(1, len(nums)-1):
    if nums[idx-1] < nums[idx] > nums[idx+1]:
        peaks.append((idx, nums[idx]))
    if nums[idx-1] > nums[idx] < nums[idx+1]:
        troughs.append((idx, nums[idx]))
        
print(peaks) # [(2, 3), (5, 5), (13, 11)]
print(troughs) # [(3, 2), (9, 1)]

First loop through to find all the peaks and troughs, and then find the top five

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template