I am looking for an efficient way to find the maximum value and corresponding index along the first axis of a 3D array using Numpy.
Context:
I am working with data stored in a 3D array z.shape() = (t, x, y) and have taken a Fourier transform along the t axis using
spectrum = np.fft.fft(z, axis=0)
spectrum.shape(f, x, y)
Here, f is the frequency space, having the same size as t.
I need to construct an array peak_vals.shape() = (x, y) which holds the highest value of the transformed data for each x- and y-coordinate. Moreover, I need to store the frequency corresponding to each peak: peak_freqs.shape() = (x, y)
I already have a function that computes the frequencies corresponding to the Fourier transform:
def freq_arr(t):
"""Determine the frequency space that a DFT of vector t would have"""
samp_freq = 1/(t[1]-t[0])
return np.arange(len(t)) * samp_freq / len(t)
To find the peak along the f axis, I came up with:
peak_vals = np.amax(spectrum, axis=0)
How can I find the frequency corresponding to these peaks? I would like to construct a function
def peaks(freqs, spectrum):
peak_vals = np.amax(spectrum, axis=0)
# do something
return peak_vals, peak_freqs
I want to avoid for-loops since I will be working with large arrays.
np.argmaxreturns the index wherenp.amaxoccurs.