0

I have a text file which contain two rows. I want to find local maximums of first row. I am trying below code, but I do not know why I get this error: "x must be a 1D array"

f= open ('ttt.txt', 'r')
data = f.readlines()
for line in data:
    c=line.split(' ')[0]
    d=float (c)
    a= np.array (d)
peaks, _ = find_peaks(a, height=0)

The input is like this:

0 5 
1 5
2 5
3 6
1 6
0 7
0 6
0.01 5
0.4 5
0.001 5
0.3 6
0.7 6
1.5 7
4 6
2 5
0.1 6
0 6

The output should be:

3 6
0.4 5
4 6
Zahra
  • 43
  • 8

2 Answers2

1

a should be a list, however, you are not making a list.

f = open ('ttt.txt', 'r')
data = f.readlines()
a = [float(line.split()[0]) for line in data]
a = np.array(a)
peaks, _ = find_peaks(a, height=0)
Jay Ke
  • 26
  • 4
  • That is working. Thank you. But how could I know that "a" should be a list, because I had an error which was "x must be a 1D array". – Zahra Jul 23 '19 at 11:03
  • I guess `x` is a variable name in `find_peaks` :) – Jay Ke Jul 24 '19 at 05:12
0

You can use argrelextrema from scipy.signal. It returns the index in the array.

Also, to load data from file, you can use numpy.loadtxt. It returns data in a numpy array (ready to use).

Here the code:

# Import modules
import numpy as np 
from scipy.signal import argrelextrema

# Load the data from text file
data = np.loadtxt('ttt.txt')

# Get local maxima from the first column
index = argrelextrema(data[:, 0], np.greater)

print(index)
# (array([ 3,  8, 13], dtype=int64),)
print(data[index])
# [[3.  6. ]
#  [0.4 5. ]
#  [4.  6. ]]

Related topic

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40