#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ENGG1811. Illustrating numpy dtype """ import numpy as np # numpy array: # data types of elements array1 = np.array([1, 2, 3, -3, -5]) # An attribute of a numpy array is its dtype # # A requirement is that all the elements in # the array must have the same dtype # # Since all the elements in array1 are integers, # the dtype of array 1 is 'int64' # # You can find out about the dtype by using # the command array1.dtype # dtype('int64') # Let us look at another array array2 = np.array([1.1, 2.2, 3, -3, -5]) # The elements of array2 are either float or integer # The dtype will be the more general of the two types array2.dtype # dtype('float64') # Since the dtype of array1 is dtype('int64') # Let us try the following array1[1] = 5.7 print(array1[1]) # 5 # Fractional part is dropped # # The lesson is that it is important to know the # dtype of a numpy array # A good practice is to specify the dtype when # initialising an array, so that you know array3 = np.array([1, 2, 3, -3, -5], dtype = int) array4 = np.array([1, 2, 3, -3, -5], dtype = float) # You can change the dtype by using .astype # array3.dtype # dtype('int64') array3 = array3.astype(float) array3.dtype # dtype('float64')