Videos
In [7]: np.array([1.0])
Out[7]: array([1.])
For a single item array:
In [8]: np.array([1.0]).item()
Out[8]: 1.0
In [9]: np.array([1.0]).tolist()
Out[9]: [1.0]
For a single item 1d array:
In [10]: np.array([1.0])[0]
Out[10]: 1.0
Note that the type of the selection differs with the method. Often that doesn't matter.
In [11]: type(Out[10])
Out[11]: numpy.float64
In [12]: type(Out[8])
Out[12]: float
In [13]: type(Out[9][0])
Out[13]: float
If the array is 0d, item is best
In [14]: np.array(1.0).item()
Out[14]: 1.0
In [15]: np.array(1.0)[0]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-15-23b6eb4e1c33> in <module>
----> 1 np.array(1.0)[0]
IndexError: too many indices for array
In [16]: np.array(1.0)[()]
Out[16]: 1.0
To get an integer, instead of a float, you have to do an int conversion at some point, either in the array (with astype) or after.
int(nparray[0])
hope it helps!
When you save a Python object (non-array), numpy wraps it in an array. The object is pickled:
In [112]: np.save('test.npy', {'foo':34})
In newer numpy versions, you have to explicitly allow it to load pickled items:
In [113]: data = np.load('test.npy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-113-c5835e6fb31e> in <module>
----> 1 data = np.load('test.npy')
/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
451 else:
452 return format.read_array(fid, allow_pickle=allow_pickle,
--> 453 pickle_kwargs=pickle_kwargs)
454 else:
455 # Try a pickle
/usr/local/lib/python3.6/dist-packages/numpy/lib/format.py in read_array(fp, allow_pickle, pickle_kwargs)
720 # The array contained Python objects. We need to unpickle the data.
721 if not allow_pickle:
--> 722 raise ValueError("Object arrays cannot be loaded when "
723 "allow_pickle=False")
724 if pickle_kwargs is None:
ValueError: Object arrays cannot be loaded when allow_pickle=False
In [115]: data = np.load('test.npy',allow_pickle=True)
In [116]: data
The result is an object dtype array with 1 element (0d)
Out[116]: array({'foo': 34}, dtype=object)
tolist can extract that object, as will item().
In [117]: data.tolist()
Out[117]: {'foo': 34}
In [118]: data.tolist()['foo']
Out[118]: 34
In [119]: data.item()
Out[119]: {'foo': 34}
In [120]: data[()]
Out[120]: {'foo': 34}
That looks like a dictionary, rather than an ndarray. Assuming you don't have multiple keys associated with the same value, you reverse the dictionary with
la_reversed = {v: k for k, v in la.items()}
so la_reversed[0] would be 'val1' and la_reversed[1] would be 'val2'.
You can get a list of values in the dictionary with list(la.values()).