NumPy arrays are the basis of all computations performed by the NumPy library. They are simple Python lists with a few additional properties. A NumPy array has the dtype
attribute, which specifies the data type of all the elements in the array.
If the array contains elements of different data types, all the elements are cast into the largest type (a process known as upcasting). A NumPy array can also be a copy or a reference to an existing NumPy array.
import numpy as np# A 2D arrayarr1 = np.array([[10, 20, 30], [-4, -5, -6]],dtype = np.double) # All the elements are doublesprint("2D NumPy array of doubles \n" + repr(arr1) + "\n")arr2 = np.array([10, 'hello', 5.8],dtype = np.str) # All the elements are stringsprint("1D NumPy array of string \n" + repr(arr2) + "\n")# Creating a reference to a NumPy arrayarr3 = arr2arr3[0] = 50print("The new value of arr2[0]: " + arr2[0])# Creating a Copyarr4 = arr2.copy()arr4[0] = '100' # arr2 will not be affectedprint("The value of arr2[0] is not altered: " + arr2[0])# Assigning an empty value to an indexarr4[2] = np.nanprint("Assigning NaN to an index: " + arr4[2])
When working with large amounts of data, hardcoding an array isn’t always possible. We can use the arange
method. It can take up to 3 parameters which will indicate the nature of the data:
import numpy as np# Creating an array from 0 to 9arr = np.arange(10)print("An array from 0 to 9\n" + repr(arr) + "\n")# Creating an array of floatsarr = np.arange(10.1)print("An array of floats\n" + repr(arr) + "\n")# The first and second arguments specify the start and end pointsarr = np.arange(-5, 5)print("An array from -5 to 5\n" + repr(arr) + "\n")# Third argument specifies the steparr = np.arange(-10, 10, 4)print("An array from -10 to 10 with a step of 4\n" +repr(arr))
Like np.array
, np.arange
performs upcasting. It also has the dtype
keyword argument to manually cast the array.