Store different datatypes in one NumPy array?
One approach might be to use a record array. The "columns" won't be like the columns of standard numpy arrays, but for most use cases, this is sufficient:
>>> a = numpy.array(['a', 'b', 'c', 'd', 'e'])>>> b = numpy.arange(5)>>> records = numpy.rec.fromarrays((a, b), names=('keys', 'data'))>>> recordsrec.array([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)], dtype=[('keys', '|S1'), ('data', '<i8')])>>> records['keys']rec.array(['a', 'b', 'c', 'd', 'e'], dtype='|S1')>>> records['data']array([0, 1, 2, 3, 4])
Note that you can also do something similar with a standard array by specifying the datatype of the array. This is known as a "structured array":
>>> arr = numpy.array([('a', 0), ('b', 1)], dtype=([('keys', '|S1'), ('data', 'i8')]))>>> arrarray([('a', 0), ('b', 1)], dtype=[('keys', '|S1'), ('data', '<i8')])
The difference is that record arrays also allow attribute access to individual data fields. Standard structured arrays do not.
>>> records.keyschararray(['a', 'b', 'c', 'd', 'e'], dtype='|S1')>>> arr.keysTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'numpy.ndarray' object has no attribute 'keys'
Refering Numpy doc, there is a function named numpy.lib.recfunctions.merge_arrays
function which can be used to merge numpy arrays in different data type into either structured array or record array.
Example:
>>> from numpy.lib import recfunctions as rfn>>> A = np.array([1, 2, 3])>>> B = np.array(['a', 'b', 'c'])>>> b = rfn.merge_arrays((A, B))>>> barray([(1, 'a'), (2, 'b'), (3, 'c')], dtype=[('f0', '<i4'), ('f1', '<U1')])
For more detail please refer the link above.