# Is there an efficient method for converting numpy.ndarray to a list?

I have a Y array of shape (this is just an example, I have huge data in this shape). The array is formed with numpy vstack and hstack (I don't want to change the way I get this array as I got it with some tricky 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 data into the libsvm function, this library expects the input parameters to be in the form of a dictionary, list or tuple. Hence the code for it:

``````prob=svm_problem(y, Y1)
```

```

The above function throws an error that "xi" must be a dictionary, list or tuple. "Another way I know is to convert Y to a list iteratively. The way to do this is:

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

```

The above method works well, but is slow given the huge data I have. Is there any faster method to achieve the same?

+3

source to share

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

```

I'm not sure if it will be much faster than large 2-D arrays. Converting such arrays to simple lists of lists is inherently inefficient - which is why you are using NumPy in the first place.

+7

source

All Articles