Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to get local maxima values from 1D-array or list

I am pretty new in Python and I have a problem which I could not solve with found answers... hopefully someone can help: I need to get a list of all local maxima of a data-set which is imported from a csv-file. Values range from 0 to 0.5 or so.

I just need to get a list of those local maxima of one data row ("Werte", array or "N", list) to do statistics on them.

This is what I have got:

import numpy as np
from numpy import *

N = []   

file = open('C:/Auswertung/PEE/PEE_L_1_O_130702-1.1.csv', 'r') 
Probe = file.readline()         # lese Inhalt zeilenweise in Listen
Header = file.readline()
data = file.readlines()

for row in data:
    columns = row.split(";")       # Trenne Zeilen bei ';' 
    N.append(float(columns[1]))

Werte = np.array([N])

# one try here: only gives me a set of 1s...    
c = (diff(sign(diff(Werte))) < 0).nonzero()[0] + 1 # local max
print(c)

is there anyone who could help me find the right way to do it? Thank you a lot!

like image 225
user2795614 Avatar asked Sep 19 '13 15:09

user2795614


2 Answers

I think you are looking for argrelmax, from scipy.signal. It gives you the indices of the relative maxima of a 1d array.

from scipy.signal import argrelmax
t=linspace(-4,40,1000)
y=sin(t)
argrelmax(y)[0]

with result

[126 269 412 554 697 840 982]

to get the values, use

y[argrelmax(y)[0]]

EDIT:

notice that it does not count local maxima at the extreme of your domain.

like image 108
gg349 Avatar answered Sep 18 '22 17:09

gg349


You are on the right track. The only extra thing you need is to slice the Werke array. but I think, finding the local max can be simplified to:

 werte[1:-1][(diff(werte)[:-1]>0)*(diff(werte)[1:]<0)]

@Jamine was quite right, & instead of * makes it reads better.

like image 23
CT Zhu Avatar answered Sep 18 '22 17:09

CT Zhu