Search code examples
pythonarraysnumpymat-filetolist

How to convert a numpy.ndarray type into a list?


I want to read a matfile in python and then export the data in a database. in order to do this I need to have the data type as list in python. I wrote the code below:

import scipy.io as si
import csv

a = si.loadmat('matfilename')
b = a['variable']                
list1=b.tolist()  

The variable has 1 row and 15 columns. when I print list1, I get the answer below: (It is indeed a list, but a list that contains only one element. It means when I call list1[0], I get the same result.):

[[array(['A'], 
  dtype='<U13'), array(['B'], 
  dtype='<U14'), array(['C'], 
  dtype='<U6'), array(['D'], 
  dtype='<U4'), array(['E'], 
  dtype='<U10'), array(['F'], 
  dtype='<U13'), array(['G'], 
  dtype='<U11'), array(['H'], 
  dtype='<U9'), array(['I'], 
  dtype='<U16'), array(['J'], 
  dtype='<U18'), array(['K'], 
  dtype='<U16'), array(['L'], 
  dtype='<U16'), array(['M'], 
  dtype='<U16'), array(['N'], 
  dtype='<U14'), array(['O'], 
  dtype='<U13')]]

While the form that I expect is:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']

Does anyone know what the problem is?


Solution

  • To my experience, that is just like MATLAB files are structured, only nested arrays.

    You can create the list yourself:

    >>> [x[0][0] for x in list1[0]]
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']