First off, apologies if this is a clear duplicate. Just getting started with numpy and I totally lack the language to describe my problem properly. Having said that, I'm looking for the correct way to do this in numpy.
I'm trying to multiply a list of ints against a corresponding row in a 2D array in numpy. The 2D array is a 10x10 checkerboard-like array, built like this:
import numpy as np
# build 10x10 array of zeros
a = np.array([[0]*10]*10)
# checkerboard out the array
a[::2,::2] = 1
a[1::2,1::2] = 1
# Result (so far so good - look at that checkerboard! Woohoo!)
print(a)
[[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1 0 1]]
Now, I want to build my range of ints to multiply against my 2D checkerboard:
b = np.array(range(5,15))
print(b)
[ 5 6 7 8 9 10 11 12 13 14]
Looks range-y to me and 10 values long - perfect! Now, in order to solve this, I've enumerated and looped through b (my list of ints), and manually multiplied the corresponding row against the int like this:
for i, n in enumerate(b):
a[i] = a[i] * n
print(a)
[[ 5 0 5 0 5 0 5 0 5 0]
[ 0 6 0 6 0 6 0 6 0 6]
[ 7 0 7 0 7 0 7 0 7 0]
[ 0 8 0 8 0 8 0 8 0 8]
[ 9 0 9 0 9 0 9 0 9 0]
[ 0 10 0 10 0 10 0 10 0 10]
[11 0 11 0 11 0 11 0 11 0]
[ 0 12 0 12 0 12 0 12 0 12]
[13 0 13 0 13 0 13 0 13 0]
[ 0 14 0 14 0 14 0 14 0 14]]
Nice! While this is what I want to achieve and it works, after having seen the power numpy has in working with arrays like this, is this the preferred numpy way?
a * b[:, None]. Also note that for creatingbyou could do:np.arange(5,15)