从整数创建一个numpy数组

时间:2016-03-01 03:29:48

标签: arrays numpy

我使用numpy从整数输入创建了一个乘法表。我从整数中创建了一个列表,并创建了一个整数形状的数组,但似乎我最终以非numpy方式做事。有没有更多的numpionic方式这样做?

TY

db.collection.update({_id: _id}, {}, {upsert: true});

2 个答案:

答案 0 :(得分:2)

这是一种使用NumPy强大的broadcasting功能的矢量化方法 -

def multiplication_table_vectorized(n):
    base = np.arange(n)+1
    return base[:,None]*base

运行时测试 -

In [33]: n = 100

In [34]: np.allclose(multiplication_table(n),multiplication_table_vectorized(n))
Out[34]: True

In [35]: %timeit multiplication_table(n)
100 loops, best of 3: 10.1 ms per loop

In [36]: %timeit multiplication_table_vectorized(n)
10000 loops, best of 3: 58.9 µs per loop

说明 -

让我们举一个玩具示例来解释这里的事情。

In [72]: n = 4 # Small n for toy example

In [73]: base = np.arange(n)+1 # Same as original: "base = list(range(1, n+1))"

In [74]: base                  # Checkback
Out[74]: array([1, 2, 3, 4])

In [75]: base[:,None]   # Major thing happening as we extend base to a 2D array
                        # with all elements "pushed" as rows (axis=0) and thus
                        # creating a singleton dimension along columns (axis=1)
Out[75]: 
array([[1],
       [2],
       [3],
       [4]])

In [76]: base[:,None]*base    # Broadcasting happens as elementwise multiplications
                              # take place between 2D extended version of 'base' 
                              # and original 'base'. This is our desired output.

                              # To visualize a broadcasting :
                              # |--------->
                              # |
                              # |
                              # |
                              # V

Out[76]: 
array([[ 1,  2,  3,  4],
       [ 2,  4,  6,  8],
       [ 3,  6,  9, 12],
       [ 4,  8, 12, 16]])

有关broadcasting的更多信息和示例,没有比official docs更好的了。 BroadcastingNumPy可用的最佳矢量化工具之一,允许进行此类自动扩展。

答案 1 :(得分:0)

接近此方法的一种“numpyonic”方式是矩阵乘法(具有行向量的列向量):

base = np.arange(my_int)
array = base.reshape((my_int,1)) * base