Categories
Python Answers

How to store different datatypes in one NumPy array with Python?

Spread the love

Sometimes, we want to store different datatypes in one NumPy array with Python.

In this article, we’ll look at how to store different datatypes in one NumPy array with Python.

How to store different datatypes in one NumPy array with Python?

To store different datatypes in one NumPy array with Python, we can store the values in a record array.

For instance, we write

a = numpy.array(['a', 'b', 'c', 'd', 'e'])
b = numpy.arange(5)
records = numpy.rec.fromarrays((a, b), names=('keys', 'data'))

to call numpr.rec.fromarrays with (a, b) and the names argument set to a tuple with the column names.

Then we get a NumPy record array that has a list of items with the tuples for each item at the given position in each tuple.

We can then get the values with the keys like

keys = records['keys']

to get the values in a.

Conclusion

To store different datatypes in one NumPy array with Python, we can store the values in a record array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *