I am working with 4D data set, where I have a nested for loop (4 loops). The for loop works, but it takes a while to run: ~5 minutes. I am trying to write this properly with list comprehension instead, but I am getting confused on exactly how to do this given my nested loops:
data = np.random.rand(12, 27, 282, 375)
stdev_data = np.std(data, axis=1)
## nested for loop
count = []
for i in range(data.shape[0]):
for j in range(data.shape[1]):
for lat in range(data.shape[2]):
for lon in range(data.shape[3]):
count.append((data[i, j, lat, lon] < -1.282 * stdev_data[i, lat, lon]).sum(axis=0))
reshape_counts = np.reshape(count, data.shape)
This is my attempt at the list comprehension:
i, j, lat, lon = data.shape[0], data.shape[1], data.shape[2], data.shape[3]
print(i, j, lat, lon)
test_list = [[(data < -1.282 * stdev_data).sum(axis=0) for lon in lat] for j in i]
I get an error saying 'int' object is not iterable. How do I rewrite my nested for loop in the form of list comprehension to speed up the process?