Jannat Arora
Jannat Arora

Reputation: 2989

Is there an efficient method to convert numpy.ndarray to list?

I have an array Y of the form(it is just an example, i have a huge data in this form). The array is formed by using numpy's vstack and hstack (i.e I don't want to change how I obtain this array as I have obtained it by some complex operations):

 Y=array([[1,  1,2],
        [1,  2,0],
        [-1, 3,1],
        [-1, 2,2]])
y=[1,1,-1,-1]
Y1=list(Y)

Now I am inputting the data to a libsvm function, this library expects the input parameters to be in dictionary, list or tuple form. Therefore, the code for the same is:

prob=svm_problem(y, Y1)

The above function throws an error that 'xi should be a dictionary, list or tuple'. The other way that I know is to convert Y to list iteratively. The manner to do it is:

Y1=[] 
for i in range(0, Y.shape[0]):
      Y1.append(list(Y[i])

The above method works well but is slow considering the huge data that I have. Is there any faster method to accomplish the same?

Upvotes: 4

Views: 6567

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601371

>>> Y.tolist()
[[1, 1, 2], [1, 2, 0], [-1, 3, 1], [-1, 2, 2]]

I'm not sure if this will be much faster than what you have for large two-dimensional arrays. Converting such arrays to plain lists of lists is an inherently inefficient operation -- that's why you use NumPy in the first place.

Upvotes: 7

Related Questions