0

I have a=[[1 2 ... 3][4 5 ... 6]...[7 8 ... 9]].
I need a=[[[1 1 1] [2 2 2] ... [3 3 3]][[4 4 4] [5 5 5] ... [6 6 6]]...[[7 7 7] [8 8 8] ... [9 9 9]]]

I basically need each element in a to become a tuple of 3 values of itself.

Sibi
  • 2,221
  • 6
  • 24
  • 37

1 Answers1

2

Tile 3 times on a columnar version and finally map to tuples, like so -

map(tuple,np.tile(a.ravel()[:,None],(1,3)))

If you are looking for a 3D array as listed in the expected output in the question, you could do -

np.tile(a[:,:,None],(1,1,3))

Sample run -

In [32]: a
Out[32]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [33]: map(tuple,np.tile(a.ravel()[:,None],(1,3)))
Out[33]: 
[(1, 1, 1),
 (2, 2, 2),
 (3, 3, 3),
 (4, 4, 4),
 (5, 5, 5),
 (6, 6, 6),
 (7, 7, 7),
 (8, 8, 8),
 (9, 9, 9)]

In [34]: np.tile(a[:,:,None],(1,1,3))
Out[34]: 
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

       [[4, 4, 4],
        [5, 5, 5],
        [6, 6, 6]],

       [[7, 7, 7],
        [8, 8, 8],
        [9, 9, 9]]])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Is there any way to get square brackets and no commas? :p – Sibi Jul 07 '16 at 11:15
  • @Sibi Use without map : `np.tile(a.ravel()[:,None],(1,3))`. – Divakar Jul 07 '16 at 11:15
  • 1
    Are you dealing with [`np.matrix` or `np.array`](http://stackoverflow.com/questions/4151128/what-are-the-differences-between-numpy-arrays-and-matrices-which-one-should-i-u)? – Divakar Jul 07 '16 at 11:30
  • Well then most probably you are just confusing yourself with the printing of arrays, which has nothing to do with how outputs are generated. The commas are just to show different elements of the input. Did you even try the code? – Divakar Jul 07 '16 at 11:34
  • `>>> a [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> np.tile(a[:,:,None],(1,1,3)) Traceback (most recent call last): File "", line 1, in TypeError: list indices must be integers, not tuple` – Sibi Jul 07 '16 at 11:43
  • @Sibi You said `a` is a NumPy array, so for the sample case I did this : `a = np.arange(9).reshape(3,3)+1` to create `a`. This is a list : `a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]`, not a NumPy array. – Divakar Jul 07 '16 at 11:44
  • Is this a np.matrix? `>>> a=([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]]) ` – Sibi Jul 07 '16 at 11:50
  • @Sibi `type(a)` would tell you the type. If its NumPy array, you would have : `numpy.ndarray` and for `np.matrix`, you would most probably have : `numpy.matrixlib.defmatrix.matrix`. – Divakar Jul 07 '16 at 11:56
  • 1
    @Sibi because that still is not a NumPy array. Do `a = np.asarray(a)` and try again. – Divakar Jul 07 '16 at 12:01