2

What is the best way to convert such ndarray:

[[1,2,3], [4,5,6]]

to the:

[[[1],[2],[3]], [[4],[5],[6]]]

just wrap each value to array

2 Answers 2

4

You can introduce a new axis with np.newaxis/None at the end, like so -

arr[...,None]

Sample run -

In [6]: arr = np.array([[1,2,3], [4,5,6]])

In [7]: arr[...,None]
Out[7]: 
array([[[1],
        [2],
        [3]],

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

In [8]: arr[...,None].tolist() # To show it as a list for expected o/p format
Out[8]: [[[1], [2], [3]], [[4], [5], [6]]]
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it by recursively exploring the list of lists:

def wrap_values(list_of_lists):
    if isinstance(list_of_lists, list):
        return [wrap_values(el) for _,el in enumerate(list_of_lists)]
    else:
        return [list_of_lists]


xx = [[1,2,3], [4,5,6]]
yy = wrap_values(xx)   # [[[1], [2], [3]], [[4], [5], [6]]]

Comments

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.