116

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
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Framester
  • 33,341
  • 51
  • 130
  • 192
  • 7
    You might want to check out scikit-learn, which includes a LibSVM wrapper that does handle Numpy arrays natively. http://scikit-learn.org/stable/modules/classes.html#module-sklearn.svm – Fred Foo Mar 15 '12 at 14:36

1 Answers1

177

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'>
M.M
  • 2,254
  • 1
  • 20
  • 33
DSM
  • 342,061
  • 65
  • 592
  • 494