Home > Software engineering >  How to save an array for each run of 'for loop'?
How to save an array for each run of 'for loop'?

Time:04-27

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.

CodePudding user response:

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)

CodePudding user response:

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 Plotted detrended data

  • Related