Conditional averaged of numpy array based on a different

Viewed 27

I have a sequence of N images with some shape (N, x,y). I also have corresponding times for each image, which is just a 1D array of length N.

Some of these times are duplicates, so I want to average the images at the same time steps so that I have a single (x,y) image for each time. I am curious what the best pythonic way for this would be?

Essentially just groupby("time").agg("mean"), but for 2D arrays.

1 Answers

If stick to groupby() paradigm, I would suggest the following:

import numpy as np
import pandas as pd
# the number of 512x512 gray-scale images
N = 200
# the iterator function that generates random images with associated random time points
# the images are numpy 2D arrays
def get_image():
    yield [ np.random.randint(24*60*60), np.random.randint(256, size=(512, 512))]
# We generate the list of random images with associated random time points
my_images = [next(get_image()) for _ in range(N)]
df = pd.DataFrame(my_images)
df.columns = ['time_point', 'image']
df = df.sort_values('time_point').reset_index(drop=True)
# making at least some images have same time point as others
df.iloc[range(0,N,5),0] = df.iloc[range(1,N-1,5),0].values
#finally our groupby
result = df.groupby('time_point').mean()
# convert pixels back from floats to integers
result.loc['image'] = result['image'].apply(np.int64)
print(result)
Related