Marten
Marten

Reputation: 804

Can i simplify this creation of an array?

I need to create an array like this with numpy in python:

array

This is my current attempt:

array = np.zeros([3, 3])

array[0, 0] = 1
array[0, 1] = 2
array[0, 2] = 3

array[1, 0] = 2
array[1, 1] = 4
array[1, 2] = 6

array[2, 0] = 3
array[2, 1] = 6
array[2, 2] = 9

print(array)

Is there a way to simplify this, Im pretty sure there is. However, i dont know how. :(

Upvotes: 0

Views: 43

Answers (2)

anon01
anon01

Reputation: 11161

definitely :) One option that is straightforward:

arr = np.arange(1,4)
my_arr = np.vstack((arr, 2*arr, 3*arr))

or you can use broadcasting. Broadcasting is powerful and straightforward, but can be confusing if you don't read the documentation. In this case you make a (1x3) array, a (3x1) array, then multiply them and broadcasting is used to generate a (3x3):

my_arr = np.arange(1,4) * np.array([1,2,3]).reshape(-1,1)

output:

array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81594

You don't have to create an array full of zeros then assign each element individually, you can pass a list literal to np.array:

np.array([[1, 2, 3],
          [2, 4, 6],
          [3, 6, 9]])

Upvotes: 1

Related Questions