Numpy: how to mass an array?

I would like to create a 3D array in numpy like this:

[ 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 good way to write it?

+3


source to share


3 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]]])

      

+6


source


If you want a 1-D array (again, it's not clear what exactly you want), you can do something like:

np.mod(np.arange(10),2)
Out[4]: array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

      



which, of course, can be changed if necessary. But I think Bernie's answer is much better and clearer.

+1


source


@Bernie's method is great. A faster way to achieve the same element might be to move the elements (practically) around rather than copying a lot of the pair [0, 1]

. You can do the following:

import numpy as np
A1 = np.concatenate([np.zeros(108), np.ones(108)]).reshape((2,108))
A2 = A1.transpose()
A3 = A2.reshape((6,6,6))

      

The first line initializes a group of ones and zeros and packs them into an array 2x108

. The second line hardly turns it into an array 108x2

. The last line then slices the array so that it is 6x6x6

and looks like what you are looking for.

The only thing to pay attention to is the number of items. Suppose you want to get the final 3D array 6x6x6

like in my example, you multiply the length of the whole axis (which gives us 216) and then divide by 2 (= 108). This number is equal to the number and zeros, and the number used in the function call .reshape((2, n))

.

The reason it is so fast is because initializing vectors of zeros or ones is really fast, faster than copying an arbitrary array. Then the moving elements, for example, which do .transpose()

and .reshape()

barely change the way they reference the elements, instead of moving the elements themselves in memory.

+1


source







All Articles