跨多维数组的矢量化NumPy空间

时间:2017-10-11 17:23:33

标签: python numpy vectorization

假设我有2个numpy 2D数组,分钟和最大值,它们将始终是彼此相同的维度。我想创建第三个数组,结果,这是将linspace应用于max和min值的结果。是否有一些“numpy”/矢量化方式来做到这一点?示例非矢量化代码如下所示,以显示我想要的结果。

        public ConsumerResponseModel MapConsumer(IEnumerable<ConsumerResourceModel> res)
    {
        var responseModel = new ConsumerResponseModel {consumers = new List<Consumer>()};
        var consumerResourceModels = res as IList<ConsumerResourceModel> ?? res.ToList();
        foreach (var item in consumerResourceModels)
        {
            foreach(var consumerData in item.consumerData)
            {
                  var consumer = Mapper.Map<Consumer>(consumerData);

                  foreach(var membership in item.Memberships)
                  {
                       consumer.memberships.Add(Mapper.Map<Membership>(membership);
                  }
                responseModel.consumers.Add(consumer);
             }
        }
        return responseModel;
    }

2 个答案:

答案 0 :(得分:6)

这是基于this post的一种矢量化方法,用于涵盖通用的n-dim案例 -

def create_ranges_nd(start, stop, N, endpoint=True):
    if endpoint==1:
        divisor = N-1
    else:
        divisor = N
    steps = (1.0/divisor) * (stop - start)
    return start[...,None] + steps[...,None]*np.arange(N)

示例运行 -

In [536]: mins = np.array([[3,5],[2,4]])

In [537]: maxs = np.array([[13,16],[11,12]])

In [538]: create_ranges_nd(mins, maxs, 6)
Out[538]: 
array([[[  3. ,   5. ,   7. ,   9. ,  11. ,  13. ],
        [  5. ,   7.2,   9.4,  11.6,  13.8,  16. ]],

       [[  2. ,   3.8,   5.6,   7.4,   9.2,  11. ],
        [  4. ,   5.6,   7.2,   8.8,  10.4,  12. ]]])

答案 1 :(得分:0)

从Numpy 1.16.0版开始,non-scalar start and stop are now supported

因此,现在您可以执行以下操作:

assert np.__version__ > '1.17.2'

mins = np.random.rand(2,2)
maxs = np.random.rand(2,2)

# Number of elements in the linspace
x = 3

results = np.linspace(mins, maxs, num=x)

# And, if required
results = np.rollaxis(results, 0, 3)