[Tutor] Converting a numpy matrix to a numpy array

Peter Otten __peter__ at web.de
Mon Apr 4 09:37:00 CEST 2011


David Crisp wrote:

>>>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()],
>> dtype=object).transpose()
>> array([[0, 0, x],
>> [0, 1, o],
>> [0, 2, o],
>> [1, 0, o],
>> [1, 1, x],
>> [1, 2, x],
>> [2, 0, o],
>> [2, 1, x],
>> [2, 2, o]], dtype=object)
>>
>> If that's not good enough you may also ask on the numpy mailing list.
> 
> Thanks Peter,
> 
> That appears to do what I want, in a way.    How does this work if you
> have a matrix which is of variable size?   For instance,  some of my
> data will create a 10 by 10 matrix but some will create a 40 by 40
> matrix, Or for that matter any size.    I notice your example
> specifically states there will be 9 outputs ( tupples? )   what if I
> want to say "just create as many tuples as you need to use to
> transpose the data"

You can find out the size of the matrix with the shape attribute:

>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> a.shape
(3, 4)

Use that to calculate the values needed to replace the constants in my 
previous post. Try to make do without the spoiler below!












































>>> def process(a, dtype=object):
...     x, y = a.shape
...     n = x*y
...     return np.array([np.arange(n)//y, np.arange(n)%y, a.flatten()], 
dtype=dtype).transpose()
...                                                                                             
>>> a = np.arange(12).reshape(3, 4)
>>> a                              
array([[ 0,  1,  2,  3],           
       [ 4,  5,  6,  7],           
       [ 8,  9, 10, 11]])
>>> process(a, int)
array([[ 0,  0,  0],
       [ 0,  1,  1],
       [ 0,  2,  2],
       [ 0,  3,  3],
       [ 1,  0,  4],
       [ 1,  1,  5],
       [ 1,  2,  6],
       [ 1,  3,  7],
       [ 2,  0,  8],
       [ 2,  1,  9],
       [ 2,  2, 10],
       [ 2,  3, 11]])
>>> b = np.array(list(
... "xoo"
... "oxx"
... "oxo")).reshape(3, 3)
>>> process(b, object)
array([[0, 0, x],
       [0, 1, o],
       [0, 2, o],
       [1, 0, o],
       [1, 1, x],
       [1, 2, x],
       [2, 0, o],
       [2, 1, x],
       [2, 2, o]], dtype=object)




More information about the Tutor mailing list