简体   繁体   中英

Python Numpy Indexing in 2 Dimensional Array

I'm and old Codger and new to Python and having a problem understanding how to index through a 2 dimensional array even though I have read many tutorials they all seem to use integers so perhaps I am missing something.

In VB I can write

Sub testindex()
Dim mymatrix(10, 10)
For i = 1 To 10
For j = 1 To 10
mymatrix(i, j) = i * j
Debug.Print mymatrix(i, j) & " ,";
Next j
Next i
End Sub

I cannot find the equivalent for Python. How can I achieve the desired results?

The most literal translation is

mymatrix=np.zeros((10,10),int)

for i in range(10):
   for j in range(10):
      mymatrix[i,j]=i*j        

In [637]: print(mymatrix)
[[ 0  0  0  0  0  0  0  0  0  0]
 [ 0  1  2  3  4  5  6  7  8  9]
 [ 0  2  4  6  8 10 12 14 16 18]
 ...
 [ 0  8 16 24 32 40 48 56 64 72]
 [ 0  9 18 27 36 45 54 63 72 81]]

Or you may want to use

 mymatrix[i,j]=(i+1)*(j+1)

to produce

array([[  1,   2,   3,   4,   5,   6,   7,   8,   9,  10],
       [  2,   4,   6,   8,  10,  12,  14,  16,  18,  20],
       ...
       [  9,  18,  27,  36,  45,  54,  63,  72,  81,  90],
       [ 10,  20,  30,  40,  50,  60,  70,  80,  90, 100]])

But there are faster, better ways of doing that in numpy .

One multiplies a row vector times a column one:

np.arange(1,11)[:,None]*np.arange(1,11)[None,:]

A clean way to get your desired matrix would be vector multiplication. In your example it would be:

import numpy as np

a = np.arange(1, 11) # create range [1, 10] (with shape (10, )
b = np.expand_dims(a, 2) # ensure you have shape (10, 1) - a proper vector
c = b*b.T

so

print(c)

outputs:

[[  1   2   3   4   5   6   7   8   9  10]
[  2   4   6   8  10  12  14  16  18  20]
[  3   6   9  12  15  18  21  24  27  30]
[  4   8  12  16  20  24  28  32  36  40]
[  5  10  15  20  25  30  35  40  45  50]
[  6  12  18  24  30  36  42  48  54  60]
[  7  14  21  28  35  42  49  56  63  70]
[  8  16  24  32  40  48  56  64  72  80]
[  9  18  27  36  45  54  63  72  81  90]
[ 10  20  30  40  50  60  70  80  90 100]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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