Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy : how to fill an array smartly?

I would like to create an 3D array in numpy as follow :

[ 0 1 0 1 0 1
  0 1 0 1 0 1
  0 1 0 1 0 1
  0 1 0 1 0 1
  0 1 0 1 0 1 ] ...

Is there a nice way to write it ?

like image 937
NicoCati Avatar asked Jul 04 '26 13:07

NicoCati


1 Answers

Using np.tile:

import numpy as np
a = np.array([0, 1])
my_tiled_array = np.tile(a, (3, 3))

Result:

array([[0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1]])

Edit:
As @DSM suggests in a comment, if you really want a 3D array -- which is not entirely clear to me from your code sample -- you can use:

my_3d_tiled_arr = np.tile(a, (3, 3, 3))

Result:

array([[[0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1]],

       [[0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1]],

       [[0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1]]])
like image 180
mechanical_meat Avatar answered Jul 07 '26 03:07

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!