Skip to content Skip to sidebar Skip to footer

Numpy: Finding Minimum And Maximum Values From Associations Through Binning

Prerequisite This is a question derived from this post. So, some of the introduction of the problem will be similar to that post. Problem Let's say result is a 2D array and values

Solution 1:

Approach #1

Again, the most intuitive ones would be with numpy.ufunc.at. Now, since, these reductions would be performed against the existing values, we need to initialize the output with max values for minimum reductions and min values for maximum ones. Hence, the implementation would be -

min_result[-y_mapping, x_mapping] = values.max()
max_result[-y_mapping, x_mapping] = values.min()

np.minimum.at(min_result, [-y_mapping, x_mapping], values)
np.maximum.at(max_result, [-y_mapping, x_mapping], values)

Approach #2

To leverage np.ufunc.reduceat, we need to sort data -

m,n = max_result.shape
out_dtype = max_result.dtype
lidx = ((-y_mapping)%m)*n + x_mapping

sidx = lidx.argsort()
idx = lidx[sidx]
val = values[sidx]

m_idx = np.flatnonzero(np.r_[True,idx[:-1] != idx[1:]])
unq_ids = idx[m_idx]

max_result_out.flat[unq_ids] = np.maximum.reduceat(val, m_idx)
min_result_out.flat[unq_ids] = np.minimum.reduceat(val, m_idx)

Post a Comment for "Numpy: Finding Minimum And Maximum Values From Associations Through Binning"