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.

1 Answer 1

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]]])
Sign up to request clarification or add additional context in comments.

9 Comments

Is there any way to get square brackets and no commas? :p
@Sibi Use without map : np.tile(a.ravel()[:,None],(1,3)).
Are you dealing with np.matrix or np.array?
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?
@Sibi because that still is not a NumPy array. Do a = np.asarray(a) and try again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.