简体   繁体   English

以pythonic方式填充2D numpy数组

[英]filling a 2D numpy array in a pythonic way

I am trying to populate a 2D numpy array. 我正在尝试填充2D numpy数组。 In my experience, the following is not going to scale up well with array sizes. 以我的经验,以下数组大小并不能很好地扩展。

x=np.array([2,3,4])
y=np.array([1,3,9,13])
mat=np.zeros((x.size,y.size))
for i in range(nx):
 for j in range(ny):
   if x[i] > y[j]:
        mat[i,j] = 1
   else:
        mat[i,j] = -1

Ideally, I would like to use list comprehension like It would be simple if it was 1D only 理想情况下,我想使用列表推导,例如仅使用一维将很简单

mat=np.asarray([foo(x_) for x_ in x])

but how to generalize this to 2D np.arrays? 但是如何将其推广到二维np.arrays? Other numpy based solutions are also suitable, but efficiency is the key metric here 其他基于numpy的解决方案也适用,但效率是此处的关键指标

It is possible to build 2 dimensional nested list comprehensions: 可以构建二维嵌套列表推导:

mat = np.array([[1 if x_ > y_ else -1 for y_ in y] for x_ in x])

However, this can become pretty unreadable, and is not much different from for loops as far performance scaling is concerned. 但是,这可能变得非常难以理解,并且就性能扩展而言,它与for循环没有太大区别。 Broadcasting and vectorization will usually work better with larger arrays: 广播和矢量化通常在较大的数组上会更好地工作:

mat = (x[:, None] > y[None, :]) * 2 - 1

Your mat : 您的mat

In [352]: mat
Out[352]: 
array([[ 1., -1., -1., -1.],
       [ 1., -1., -1., -1.],
       [ 1.,  1., -1., -1.]])

broadcasting x against y : y广播x

In [353]: x[:,None]>y
Out[353]: 
array([[ True, False, False, False],
       [ True, False, False, False],
       [ True,  True, False, False]], dtype=bool)

turn that boolean mask into 1/-1 array with where : 将该布尔型掩码转换为1 / -1数组, where

In [354]: np.where(x[:,None]>y,1,-1)
Out[354]: 
array([[ 1, -1, -1, -1],
       [ 1, -1, -1, -1],
       [ 1,  1, -1, -1]])

Or you could turn the boolean into a 0/1 array, and scale that to fit 或者,您可以将布尔值转换为0/1数组,并对其进行缩放以适合

(x[:,None]>y).astype(float)*2-1

A double loop over two 1d arrays or lists can often be cast as an outer operation like this. 这样,通常可以将两个1d数组或列表上的双循环转换为outer操作。

try: 尝试:

x=np.array([2,3,4])
y=np.array([1,3,9,13])
a = (x.reshape(x.shape[0], 1) - y) > 0  # a=(x.reshape(-1, 1) - y) > 0
a = a.astype(int)*2 -1 

If using numpy: 如果使用numpy:

import numpy as np
nx = x.size
ny = y.size
mat = np.sign(x * np.atleast_2d(np.ones(ny)).T - np.ones(nx) * np.atleast_2d(y).T)
mat[np.where(mat==0)] = -1

numpy will take care regarding efficiency (whatever it means here). numpy将注意效率(无论在这里意味着什么)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM