Posted under » Python Data Analysis on 18 March 2025
< From numpy introduction
NumPy supports a greater variety of numerical types. Eg scalar types.
They are bool_, int_, intc, intp, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float_, float16, float32, float64, complex_, complex64 and complex128. While the default data type is floating point (np.float64), you can explicitly specify which data type you want using the dtype keyword. You don't have to memorise or specify them like a database structure because numpy will assign the types automatically.
You can explicitly convert or cast an array from one dtype to another using ndarray’s astype method which makes numpy powerful and flexible.
arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1]) arr.astype(np.int32) Out: array([ 3, -1, -2, 0, 12, 10], dtype=int32)
The following example define a structured data type called student with a string field 'name', an integer field 'age' and a float field 'marks'. This dtype is applied to ndarray object.
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) print (student) out: [('name', 'S20'), ('age', 'i1'), ('marks', '<f4')] a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student) print(a) out: [('abc', 21, 50.0), ('xyz', 18, 75.0)]
Some basic types