NumPy is a Python library for scientific computing in Python programming. In this tutorial, you will learn how to add, delete, sort and manipulate elements in NumPy arrays in a variety of ways.
NumPy provides a multidimensional array object and other derived arrays, such as mask arrays and mask multidimensional arrays.
Why use NumPy
NumPy provides an ndarray object that can be used to manipulate arrays of any dimension. Ndarray represents an array of N dimensions, where N is an arbitrary number. This means that NumPy arrays can be of any dimension.
NumPy has many advantages over Python's List. We can perform high performance operations on NumPy arrays, such as:
- Sort Group Members
- Mathematical and logical operations
- Input/Output Function
- Statistics and Linear Algebraic Operations
Install NumPy
To install NumPy, you need Python and Pip on your computer first.
Run the following commands in the terminal:
pip install numpy
Then you can import NumPy into the script, as follows:
import numpy
Add array elements
The append() method of the NumPy module can be used to add elements to the NumPy array.
The grammar of append() is as follows:
numpy.append(array, value, axis)
value is appended to the end of the array and returns a ndarray containing all elements.
The parameter axis is an optional integer that defines how arrays are displayed. If not specified, the array structure will flatten out and usage will be demonstrated later.
In the following example, an array is declared first, and then more values are added to the array using the append method:
import numpy a = numpy.array([1, 2, 3]) newArray = numpy.append (a, [10, 11, 12]) print(newArray) # Output: [12 3 10 11 12]
Add a column
You can also insert a column using NumPy's append() method.
In the following example, we create a two-dimensional array and insert two columns:
import numpy a = numpy.array([[1, 2, 3], [4, 5, 6]]) b = numpy.array([[400], [800]]) newArray = numpy.append(a, b, axis = 1) print(newArray) """ //Output: [[ 1 2 3 400] [ 4 5 6 800]] """
If the axis parameter is not used, the output is:
[ 1 2 3 4 5 6 400 800]
This is the flattening of the array structure.
In NumPy, you can also insert elements or columns using insert(). The difference between the two is that the insert() method can specify which index to add elements, but the append() method adds a value at the end of the array.
Consider the example below:
Consider the following examples:
import numpy a = numpy.array([1, 2, 3]) newArray = numpy.insert(a, 1, 90) print(newArray) # Output: [1 902 3]
Here the insert() method adds elements at index 1. In Python, the array index starts at 0.
Append one line
You can also add rows to an array using the append() method, as simple as attaching elements to an array:
import numpy a = numpy.array([[1, 2, 3], [4, 5, 6]]) newArray = numpy.append(a, [[50, 60, 70]], axis = 0) print(newArray) """ //Output " [[ 1 2 3] [ 4 5 6] [50 60 70]] """
Delete elements
NumPy array elements can be deleted using the delete() method of the NumPy module:
import numpy a = numpy.array([1, 2, 3]) newArray = numpy.delete(a, 1, axis = 0) print(newArray) # Output: [13]
In this example, we have a one-dimensional array that deletes elements at index 1 from the array by delete().
Delete one row
Similarly, you can delete rows with the delete() method.
In the following example, we delete a line from a two-dimensional array:
import numpy a = numpy.array([[1, 2, 3], [4, 5, 6], [10, 20, 30]]) newArray = numpy.delete(a, 1, axis = 0) print(newArray) """ //Output: [[ 1 2 3] [10 20 30]] """
In the delete() method, the array is given first, and then the index of the element to be deleted is given. In the previous example, we deleted the element with index 1.
Check whether the NumPy array is empty
You can use the size method to return the total number of elements in an array.
In the following example, there is an if statement that checks for elements in an array by ndarray.size, where ndarray can be any given NumPy array:
import numpy a = numpy.array([1, 2, 3]) if(a.size == 0): print("The given Array is empty") else: print("The array = ", a) # Output: The array = [123]
In the code above, there are three elements in the array, so it is not empty, and the judgement returns false. If there are no elements in the array, the if condition becomes true and empty messages are printed. If the array equals:
a = numpy.array([])
The above code will output:
The given Array is empty
Index of Find Value
To find the index corresponding to the value, you can use the where() method of the NumPy module, as shown in the following example:
import numpy a = numpy.array([1, 2, 3, 4, 5]) print("5 is found at index: ", numpy.where(a == 5)) # Output: 5 is found at index: (array ([4]),)
If you only want to get the index, you can write as follows:
import numpy a = numpy.array([1, 2, 3, 4, 5]) index = numpy.where(a == 5) print("5 is found at index: ", index[0]) #Output: 5 is found at index: [4]
NumPy array slice
Array slicing is the process of extracting subsets from a given array. You can slice an array with a colon (:) operator and specify the start and end positions of the array index, such as:
array[from:to]
The following example extracts elements from index 2 to index 5:
import numpy a = numpy.array([1, 2, 3, 4, 5, 6, 7, 8]) print("A subset of array a = ", a[2:5]) # Output: A subset of array a = [345]
If you want to extract the last three elements, you can do this by using negative slices, as follows:
import numpy a = numpy.array([1, 2, 3, 4, 5, 6, 7, 8]) print("A subset of array a = ", a[-3:]) # Output: A subset of array a = [678]
Acting on all array elements with functions
In the following example, we will create a lambda function and pass in an array to apply it to all elements:
import numpy addition = lambda x: x + 2 a = numpy.array([1, 2, 3, 4, 5, 6]) print("Array after addition function: ", addition(a)) # Output: Array after addition function: [345 678]
In this case, a lambda function is created that increments each element by 2.
Length of NumPy array
To get the length of the NumPy array, you can use the size attribute as follows:
import numpy a = numpy.array([1, 2, 3, 4, 5, 6]) print("The size of array = ", a.size) # Output: The size of array = 6
Create NumPy arrays from list s
Suppose you have a list:
l = [1, 2, 3, 4, 5]
Now to create an array based on this list, you can use the array() method of the NumPy module:
import numpy l = [1, 2, 3, 4, 5] a = numpy.array(l) print("The NumPy array from Python list = ", a) # Output: The NumPy array from Python list = [1 234 5]
Similarly, you can create NumPy arrays from tuples using the array() method. As follows:
import numpy t = (1, 2, 3, 4, 5) a = numpy.array(t) print("The NumPy array from Python Tuple = ", a) # Output: The NumPy array from Python Tuple = [1 234 5]
Convert NumPy array to list
To convert an array to a list, you can use the tolist() method of the NumPy module.
import numpy a = numpy.array([1, 2, 3, 4, 5]) print("Array to list = ", a.tolist()) # Output: Array to list = [1, 2, 3, 4, 5]
In this code, we simply call the tolist() method, which converts an array into a list. Then print the newly created list to the output screen.
Export NumPy array to CSV
To export an array to a CSV file, you can use the savetxt() method of the NumPy module, as follows:
import numpy a = numpy.array([1, 2, 3, 4, 5]) numpy.savetxt("myArray.csv", a)
This code will generate the CSV file in the path where the Python code file is located. Of course, you can also specify a path.
The contents of the document are as follows:
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
You can delete the extra filled zeros as follows:
numpy.savetxt("myArray.csv", a,fmt='%.2f')
Sorting NumPy arrays
NumPy arrays can be sorted using the sort() method of the NumPy module:
The sort() function has an optional parameter axis (integer), which defaults to - 1. Axis specifies the axis on which we want to sort arrays. - 1 indicates that the array will be sorted according to the last axis.
import numpy a = numpy.array([16, 3, 2, 6, 8, 10, 1]) print("Sorted array = ", numpy.sort(a)) # Output: Sorted array = [12 3 6 8 10 16]
In this example, we call the sort() method in the print statement. The array a is passed to the sort function.
Normalized array
Normalized arrays refer to the process of placing the values of arrays within a defined range. For example, we want to normalize arrays between - 1 and 1, and so on.
The normalized formula is as follows:
x = (x – xmin) / (xmax – xmin)
Now apply this formula to our array. To find the maximum and minimum items in an array, you can use NumPy's max() and min() methods, respectively.
import numpy x= numpy.array([400, 800, 200, 700, 1000, 2000, 300]) xmax = x.max() xmin = x.min() x = (x - xmin)/(xmax - xmin) print("After normalization array x = \n", x) """ //Output: After normalization array x = [0.11111111 0.33333333 0. 0.27777778 0.44444444 1. 0.05555556] """
Array index
The index points to an element in the array. In the following examples, indexes in one-dimensional and two-dimensional arrays are used:
import numpy a = numpy.array([20, 13, 42, 86, 81, 9, 11]) print("Element at index 3 = ", a[3]) # Output: Element at index 3 = 86
Here is a two-dimensional array:
import numpy a = numpy.array([[20, 13, 42], [86, 81, 9]]) print("Element at index a[1][2] = ", a[1][2]) # Output: Element at index a [1] [2] = 9
The index [1] [2] represents the second row and the third column (the index starts at 0). So output 9 on the screen.
Attach a NumPy array to another array
NumPy arrays can be attached to another NumPy array using the append() method.
import numpy a = numpy.array([1, 2, 3, 4, 5]) b = numpy.array([10, 20, 30, 40, 50]) newArray = numpy.append(a, b) print("The new array = ", newArray) # Output: The new array = [12 3 4 5 10 20 30 40 50]
In this case, create two NumPy arrays a, b. Then pass two arrays to append(). When array b is passed as the second parameter, it is added to the end of array a.
summary
As you can see, NumPy arrays are very simple to use. NumPy arrays are very important when using many machine learning libraries. It can be said that NumPy is the door of artificial intelligence.