qualiaMachine qualiaMachine - 2 years ago 102
Python Question

Unable to extract object from single-item numpy array

I seem to be hitting a wall on what is likely a very simple issue to solve. I have saved out a *.npz file containing a single variable--an object of class Network (a class I wrote).

# Initialize network
burstNetwork = Network(numChs,dt,UFRs,NBPs,BDs,UFRsByChan,varyFRbyChs,minChConstBurst,createChCorrelations)
if saveData:
pd.np.savez((saveDir + "simulator.npz"), burstNetwork=burstNetwork)

When I try to read the data back in, I find that my variable is now in the form of an numpy array of size 1 that I am unable to index from, and thus unable to get my Network object back and view its attributes (my end goal).

# Load network
simulator = np.load(simFilesDir + "simulator.npz")
network = simulator['burstNetwork']

Out[43]: array(<__main__.Network object at 0x000000000AEF0C18>, dtype=object)

Indexing attempt:


IndexError Traceback (most recent call last)
<ipython-input-44-297be643431d> in <module>()
----> 1 network[0]

IndexError: too many indices for array

Please advice.

Answer Source

When indexing an array you need a tuple that matches the dimensions in length. This is 0d, so the tuple has to be 0 length, (). The item method also works.

In [922]: arr = np.array(1, dtype=object)
In [923]: arr.shape
Out[923]: ()
In [924]: arr
Out[924]: array(1, dtype=object)
In [925]: arr.item()
Out[925]: 1
In [926]: arr[()]
Out[926]: 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download