Ich benutze Scipys loadmat
Funktion, um eine Matlab-Datei in Python zu laden.Zugriff auf Elemente von numpy ndarray?
from scipy.io import loadmat
data = loadmat('data.mat')
fields = data['field']
Die Art der fields
ist 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 iterieren das Array unter Verwendung 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:
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
Fragen:
Wenn ich versuche, das erste Element x
ich eine IndexError
erhalten Zugriff auf
- Wie kommt es, wenn
type(x)
kehrtnump.ndarray
es sagt "zu viele Indizes für Array"? - Wie kann ich den Inhalt von
x
in eine Zeichenfolge extrahieren?
Hier sind die Versionen Ich verwende:
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
Können Sie 'x.shape' ausdrucken? –
@C_Z_ - Die Frage wurde aktualisiert, um 'x.shape' einzufügen, was '()' –
zurückgibt. Das ist ein 0d-Array, das Sie mit einem 0-Element-Tupel, 'x [()]', indizieren müssen. Siehe meine Antwort. – hpaulj