Numpy Array :-
In python, a numpy array is a data structure provided by the Numpy library. Where we can store same data type.
- A NumPy array is a way to store numbers in Python.
- It is faster and smaller than a normal list.
- You can do math on all the numbers at once.
- It has tools to cut, resize, and manage data
Storing Different Datatypes In One Numpy Array :-
We can archive the storing of diffrent datatype in one numpy array by following methods.
- Using Structured Arrays.
- Using the object dtype.
1.Using Structured Arrays. :-
Structured arrays allow you to define a custom data type with multiple fields, each having its own specific data type.For example, if you want to store information about people with Name (string), Age (integer), and Height (float), a structured array lets you store them together in a single array.
import numpy as np dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f8')] data = np.array([('OM', 25, 1.65), ('Raju', 30, 1.80)], dtype=dtype) print(data) print(data['name']) print(data['age'])
Output :
[(‘OM’, 25, 1.65) (‘Raju’, 30, 1.8 )]
[‘OM’ ‘Raju’]
[25 30]
2. Using the Object dtype :
You can store different types by setting the dtype = Object This approach is less memory-efficient and slower since it behaves like a Python list.
This approach allows you to store arbitrary Python objects in the array,
import numpy as np data = np.array([1, 'hello', 3.14], dtype=object) print(data)
output :
[1 'hello' 3.14]