[Tutor] Converting a numpy matrix to a numpy array

David Crisp david.crisp at gmail.com
Mon Apr 4 05:09:35 CEST 2011


On Fri, Apr 1, 2011 at 2:04 AM, Peter Otten <__peter__ at web.de> wrote:
> David Crisp wrote:
>
>> Hello,
>>
>> I have a very simple question / problem I need answered.  The problem
>> is imnot entirely sure of the correct terminology and langauge to use
>> to describe it.  (One of the reasons im using this miling list)
>>
>> I have a 2d matrix representing the X the Y and the Z value of a
>> point.  I wish to convert that matrix to an array.    What is a good
>> way of doing so?
>>
>> Eg:
>> Matrix
>> 012345
>> 0xooooo
>> 1xooooo
>> 2oxxxxx
>> 3oooooo
>> 4ooooox
>> 5ooooox
>>
>>
>> I want to convert that to a 2d array which looks like:
>> 0,0,x
>> 0,1,o
>> 0,2,o
>> 0,3,o
>> 0,4,o
>> 0,5,o
>> .......
>> 5,4,o
>> 5,5,o
>>
>> I am pretty sure it is simple.  I'm just having a brain fade.
>
> Using basic numpy:
>
>>>> import numpy as np
>>>> a = np.array(list("xoo"
> ...                   "oxx"
> ...                   "oxo")).reshape(3,3)
>>>> a
> array([['x', 'o', 'o'],
>       ['o', 'x', 'x'],
>       ['o', 'x', 'o']],
>      dtype='|S1')
>>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()]).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='|S8')
>>>> np.array([np.arange(9)//3, np.arange(9)%3,
> (a=="x").flatten()]).transpose()
> array([[0, 0, 1],
>       [0, 1, 0],
>       [0, 2, 0],
>       [1, 0, 0],
>       [1, 1, 1],
>       [1, 2, 1],
>       [2, 0, 0],
>       [2, 1, 1],
>       [2, 2, 0]])
>>>> 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"

Regards,
David


More information about the Tutor mailing list