Verych
Verych

Reputation: 441

Python: How to convert Numpy array item value type to array with this value?

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

Upvotes: 2

Views: 128

Answers (2)

FLab
FLab

Reputation: 7506

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]]]

Upvotes: 0

Divakar
Divakar

Reputation: 221684

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]]]

Upvotes: 4

Related Questions