[Tutor] Converting a numpy matrix to a numpy array

Peter Otten __peter__ at web.de
Thu Mar 31 17:04:50 CEST 2011


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.



More information about the Tutor mailing list