How to save an array for each run of 'for loop'?

Viewed 60

I have ocean temperature data having 'depth' and 'time', as data(depth,time). I want to use the 'detrend' function at each depth and save that result. So that I get as a result detrend(number of depth, time) as a one array. Depth = 42 and time = 72

for i in range(44):
depth = temp[:,i]
detrend = s.detrend(depth)

But, this is giving only last depth value calculation.

Please let me know.

2 Answers

Assuming you're using scipy.signal.detrend(), you can use the axis argument to do this without a loop. It's unclear to me which axis you're hoping to detrend, but you can pick axis=0 or axis=1 depending on which you want. So:

detrend = s.detrend(temp,axis=0)

In general, if you do want to do something like this in a loop you could create an empty array of the right size that you then write into in each iteration of the loop.

detrended = np.zeros_like(temp)
for i in range(44):
    depth = temp[:,i]
    detrended[:,i] = s.detrend(depth)

First, if you don't save the detrended data in a list or an array during the for loop it is obvious that only the last detrend will survive. Actually there is no need to use a for loop for that.

Instead of using scipy methods you can use also directly use the xarray polyfit and polyval method, which let you specify the dimension over which to detrend.

Example:

import numpy as np
import xarray as xr

#test data with linear trend
data_vars=np.arange(1000)[None,:]+np.random.randn(50,1000)*100
data=xr.DataArray(data_vars,dims=['depth','time'])

p = data.polyfit(dim='time', deg=1)
fit = xr.polyval(data['time'], p.polyfit_coefficients)
detrend = data-fit

#eg for zeroth depth
data.isel(depth=0).plot(label='raw')
detrend.isel(depth=0).plot(label='lin. detrended')
plt.legend()

Plotted detrended data

Related