Uso la funzione loadmat
di scipy per caricare un file di dati matlab in python.Come accedere agli elementi di numpy ndarray?
from scipy.io import loadmat
data = loadmat('data.mat')
fields = data['field']
Il tipo di fields
è numpy.ndarray
:
print 'fields type={}'.format(type(fields))
print 'fields dtype={}'.format(fields.dtype)
print 'fields shape={}'.format(fields.shape)
fields type=<type 'numpy.ndarray'> fields dtype=object fields shape=(5,)
I iterare l'array usando nditer
:
for x in np.nditer(fields, flags=['refs_ok']):
print 'x={}'.format(x)
print 'x type={}'.format(type(x))
print 'x dtype={}'.format(x.dtype)
print 'x shape={}'.format(x.shape)
break
x=[u'ACE'] x type=<type 'numpy.ndarray'> x dtype=object x shape=()
IndexError:
Se provo ad accedere al primo elemento di x
ottengo un IndexError
:
x[0]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-102-8c374ae22096> in <module>() 17 print 'type={}'.format(type(x)) 18 print 'dtype={}'.format(x.dtype) ---> 19 x[0] 20 break 21 IndexError: too many indices for array
Domande:
- Come venire, se
type(x)
restituiscenump.ndarray
dice "troppi indici per array"? - Come posso estrarre il contenuto di
x
in una stringa?
Qui ci sono le versioni che sto usando:
print 'python version: {}'.format(sys.version)
print 'numpy version: {}'.format(numpy.__version__)
print 'scipy version: {}'.format(scipy.__version__)
python version: 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] numpy version: 1.11.0 scipy version: 0.17.1
È possibile stampare 'x.shape'? –
@C_Z_ - ha aggiornato la domanda per includere 'x.shape', che restituisce'() ' –
Questo è un array 0d, che devi indicizzare con una tupla di elementi 0,' x [()] '. Vedi la mia risposta. – hpaulj