[Solved] Python Numpy Flat Function


A simple use of flat:

In [410]: res = np.zeros((2,3), dtype=int)
In [411]: res
Out[411]: 
array([[0, 0, 0],
       [0, 0, 0]])

In [413]: res.flat[::2]=1
In [414]: res
Out[414]: 
array([[1, 0, 1],
       [0, 1, 0]])
In [415]: res.ravel()
Out[415]: array([1, 0, 1, 0, 1, 0])

flat is a variant on flatten and ravel. Here I use it to assign 1 to every other element of the flattened array. You can see that happening in the ravel expression. It’s a bit less obvious in the 2d view of the same array.

In res[:n-k].flat[i::n+1] = v, the first [:n-k] selects some rows of res. The flat[] acts in my example, assigning values from v to ever n+1 element in the flattened array.

Again testing with a small example:

In [417]: res = np.zeros((5,5), dtype=int)
In [418]: res[:3]
Out[418]: 
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
In [419]: res[:3].flat[2::6]
Out[419]: array([0, 0, 0])
In [420]: res[:3].flat[2::6]=[1,2,3]
In [421]: res
Out[421]: 
array([[0, 0, 1, 0, 0],
       [0, 0, 0, 2, 0],
       [0, 0, 0, 0, 3],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

The use of [i::n+1] indexing ends up setting values on an diagonal.

or

In [422]: res = np.zeros((5,5), dtype=int)
In [424]: res.flat[0::6]
Out[424]: array([0, 0, 0, 0, 0])
In [425]: res.flat[0::6]=np.arange(5)
In [426]: res
Out[426]: 
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 2, 0, 0],
       [0, 0, 0, 3, 0],
       [0, 0, 0, 0, 4]])

solved Python Numpy Flat Function