Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2d numpy array into list of lists [duplicate]

I use an external module (libsvm), which does not support numpy arrays, only tuples, lists and dicts. But my data is in a 2d numpy array. How can I convert it the pythonic way, aka without loops.

>>> import numpy >>> array = numpy.ones((2,4)) >>> data_list = list(array) >>> data_list [array([ 1.,  1.,  1.,  1.]), array([ 1.,  1.,  1.,  1.])]  >>> type(data_list[0]) <type 'numpy.ndarray'>  # <= what I don't want  # non pythonic way using for loop >>> newdata=list() >>> for line in data_list: ...     line = list(line) ...     newdata.append(line) >>> type(newdata[0]) <type 'list'>  # <= what I want 
like image 509
Framester Avatar asked Mar 15 '12 14:03

Framester


People also ask

How do you convert a 2D matrix to a list in Python?

To convert from a Numpy array to list, we simply typed the name of the 2D Numpy array, and then called the Numpy tolist() method which produced a Python list as an output.

How do you convert an N dimensional array to a list in Python?

With NumPy, [ np. array ] objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned.

How do I change Ndarray to list?

To convert a NumPy array (ndarray) to a Python list use ndarray. tolist() function, this doesn't take any parameters and returns a python list for an array. While converting to a list, it converts the items to the nearest compatible built-in Python type.


1 Answers

You can simply cast the matrix to list with matrix.tolist(), proof:

>>> import numpy >>> a = numpy.ones((2,4)) >>> a array([[ 1.,  1.,  1.,  1.],        [ 1.,  1.,  1.,  1.]]) >>> a.tolist() [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]] >>> type(a.tolist()) <type 'list'> >>> type(a.tolist()[0]) <type 'list'> 
like image 83
DSM Avatar answered Sep 21 '22 11:09

DSM