2016-03-01 205 views
1

我使用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)) 

回答

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更好。 Broadcasting是可用於NumPy的最佳矢量化工具之一,允許進行這種自動擴展。

+0

感謝,這正是我一直在尋找。你能解釋一下這個回報如何運作嗎?我知道讓這個基地成爲一個ndarray,但我對如何填充返回/數學工作感到困惑。 –

+0

@TASCSolutions查看添加的評論是否有助於理解那裏發生了什麼。 – Divakar

+0

是的,我現在看得很清楚:我需要對我的整數進行排序,所以numpy可以使用它,基數[:,無]替換我的循環以獲得垂直行,然後進行廣播和基礎數學。 –

0

一個「numpyonic」方式來處理,這將是一個矩陣乘法(列向量與行向量):

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

謝謝,看來我需要另一個numpy教程,這些解決方案比我的混合方法更快,更乾淨。 –

+0

不要擔心,如果你沒有立刻得到它,我花了很長時間這種思維方式來「點擊」我 – maxymoo

相關問題