building numpy arrays with regular structure

Peter Otten __peter__ at web.de
Sat Dec 17 03:54:07 EST 2016


Seb wrote:

> Is there an easier way to write a numpy array with a regular structure?
> For example, an array with [0, 1] along the diagnal of one of the array
> dimensions, and zero elsewhere:
> 
> zz = np.array([[[0, 1], [0, 0], [0, 0]],
>                [[0, 0], [0, 1], [0, 0]],
>                [[0, 0], [0, 0], [0, 1]]])
> 
> This one is not so big, but if it were, there must be a way to code this
> properly.

Searching for "numpy assigning diagonal values" gave

https://docs.scipy.org/doc/numpy/reference/generated/numpy.fill_diagonal.html

as the first hit. So

>>> a = numpy.zeros((3,3,2), dtype=int)
>>> a
array([[[0, 0],
        [0, 0],
        [0, 0]],

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

       [[0, 0],
        [0, 0],
        [0, 0]]])
>>> numpy.fill_diagonal(a[:,:,1], 1)
>>> a
array([[[0, 1],
        [0, 0],
        [0, 0]],

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

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





More information about the Python-list mailing list