【发布时间】:2019-01-13 05:30:45
【问题描述】:
先决条件
这是一个源自post 的问题。所以,一些问题的介绍会和那篇帖子差不多。
问题
假设result 是一个二维数组,values 是一个一维数组。 values 包含与result 中的每个元素相关联的一些值。 values 中的元素到result 的映射存储在x_mapping 和y_mapping 中。 result 中的位置可以与不同的值相关联。现在,我必须找到按关联分组的值的最小值和最大值。
一个更清楚的例子。
min_result数组:
[[0, 0],
[0, 0],
[0, 0],
[0, 0]]
max_result数组:
[[0, 0],
[0, 0],
[0, 0],
[0, 0]]
values数组:
[ 1., 2., 3., 4., 5., 6., 7., 8.]
注意:这里result 数组和values 具有相同数量的元素。但情况可能并非如此。大小之间根本没有关系。
x_mapping 和 y_mapping 具有从 1D values 到 2D result(最小值和最大值)的映射。 x_mapping、y_mapping 和 values 的大小将相同。
x_mapping - [0, 1, 0, 0, 0, 0, 0, 0]
y_mapping - [0, 3, 2, 2, 0, 3, 2, 1]
这里,第一个值(values[0])和第五个值(values[4])的 x 为 0,y 为 0(x_mapping[0] 和 y_mappping[0]),因此与 result[0, 0] 相关联。如果我们计算该组的最小值和最大值,我们将分别得到 1 和 5 作为结果。所以,min_result[0, 0] 将有 1,max_result[0, 0] 将有 5。
请注意,如果根本没有关联,则result 的默认值将为零。
当前的工作解决方案
x_mapping = np.array([0, 1, 0, 0, 0, 0, 0, 0])
y_mapping = np.array([0, 3, 2, 2, 0, 3, 2, 1])
values = np.array([ 1., 2., 3., 4., 5., 6., 7., 8.], dtype=np.float32)
max_result = np.zeros([4, 2], dtype=np.float32)
min_result = np.zeros([4, 2], dtype=np.float32)
min_result[-y_mapping, x_mapping] = values # randomly initialising from values
for i in range(values.size):
x = x_mapping[i]
y = y_mapping[i]
# maximum
if values[i] > max_result[-y, x]:
max_result[-y, x] = values[i]
# minimum
if values[i] < min_result[-y, x]:
min_result[-y, x] = values[i]
min_result,
[[1., 0.],
[6., 2.],
[3., 0.],
[8., 0.]]
max_result,
[[5., 0.],
[6., 2.],
[7., 0.],
[8., 0.]]
失败的解决方案
#1
min_result = np.zeros([4, 2], dtype=np.float32)
np.minimum.reduceat(values, [-y_mapping, x_mapping], out=min_result)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-126de899a90e> in <module>()
1 min_result = np.zeros([4, 2], dtype=np.float32)
----> 2 np.minimum.reduceat(values, [-y_mapping, x_mapping], out=min_result)
ValueError: object too deep for desired array
#2
min_result = np.zeros([4, 2], dtype=np.float32)
np.minimum.reduceat(values, lidx, out= min_result)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-07e8c75ccaa5> in <module>()
1 min_result = np.zeros([4, 2], dtype=np.float32)
----> 2 np.minimum.reduceat(values, lidx, out= min_result)
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (4,2)->(4,) (8,)->() (8,)->(8,)
#3
lidx = ((-y_mapping) % 4) * 2 + x_mapping #from mentioned post
min_result = np.zeros([8], dtype=np.float32)
np.minimum.reduceat(values, lidx, out= min_result).reshape(4,2)
[[1., 4.],
[5., 5.],
[1., 3.],
[5., 7.]]
问题
如何使用np.minimum.reduceat 和np.maximum.reduceat 来解决这个问题?我正在寻找针对运行时优化的解决方案。
旁注
我正在使用 Numpy 1.14.3 版和 Python 3.5.2
【问题讨论】:
标签: python numpy array-broadcasting numpy-ufunc