从一个整数创建numpy数组
问题描述:
我使用numpy从整数输入创建了一个乘法表。我从整数创建了一个列表,并创建了一个整数形状的数组,但看起来我最终会以非numpy的方式做事。有更多的这种做法吗?从一个整数创建numpy数组
TY
def multiplication_table(n):
import numpy as np
base = list(range(1, n+1))
array_shell = np.zeros(shape=(n,n), dtype=int)
array_shell[0] = base
for row in range(1,len(base)):
array_shell[row][0] = base[row]
for row in range(1, len(base)):
for idx in range(1, len(base)):
array_shell[row][idx] = base[idx]*array_shell[row][0]
return (array_shell)
my_int = 8
print(multiplication_table(my_int))
答
下面是一个使用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
更好。 Broadcasting
是可用于NumPy
的最佳矢量化工具之一,允许进行这种自动扩展。
答
一个“numpyonic”方式来处理,这将是一个矩阵乘法(列向量与行向量):
base = np.arange(my_int)
array = base.reshape((my_int,1)) * base
+0
谢谢,看来我需要另一个numpy教程,这些解决方案比我的混合方法更快,更干净。 –
+0
不要担心,如果你没有立刻得到它,我花了很长时间这种思维方式来“点击”我 – maxymoo
感谢,这正是我一直在寻找。你能解释一下这个回报如何运作吗?我知道让这个基地成为一个ndarray,但我对如何填充返回/数学工作感到困惑。 –
@TASCSolutions查看添加的评论是否有助于理解那里发生了什么。 – Divakar
是的,我现在看得很清楚:我需要对我的整数进行排序,所以numpy可以使用它,基数[:,无]替换我的循环以获得垂直行,然后进行广播和基础数学。 –