So, in the last blog, we talked about creating arrays and indexing. This time, we delve into the functions that NumPy has to offer.
But before that, let's talk about the difference between arrays and lists.
Difference between Lists and Arrays
Although they may seem similar, arrays and lists in Python have one very basic difference. Unlike lists, arrays do not support multiple datatypes.
For example, if we take the array:
arr = np.array([[1,2,3],[4,5,6]])
And print the datatype using type(arr[0][0])
, the output is:
But if we take the array:
arr = np.array([[1,2.7,3],[4,5,6]])
And print datatype the same way, we get the output:
Appending Elements to Array
In order to append elements to an array, we follow the syntax:
np.append(<array_name>[<row index>], <element>)
The output would look like this:
Making an Array of Zeroes
Ever wanted to make an array that is filled with just zeroes? Numpy has you covered. Use:
<array_name> = np.zeros((<rows>,<columns>))
The default datatype is Float but we can turn it into int by adding another argument:
<array_name> = np.zeros((<rows>,<columns>), dtype=int)
Deleting Elements in an Array
There are different ways of and conditions for deleting elements from arrays. Let's look at some of them:
1) Deleting using Boolean Arrays
So let us take a sample array:
[[1,2,3,3,4,3,5]]
To delete all instances of the element 3, we can run:
arr = arr(arr != 3)
The resulting array is:
The way this works is that on encountering arr!=3
, it coverts the array into a boolean array where all elements satisfying this condition are considered True. So, the array would look like:
[True, True, False, False, True, False, True]
Then on running arr()
, all the elements with a True boolean value are kept. The resulting array becomes:
[1,2,4,5]
We can also put in multiple conditions such as deleting all elements that fall in a range of int m to n.
arr = arr[(arr>1) & (arr<4)]
This will follow the same process and output an array after deleting all elements that are not greater than 1 and not less than 4.
2) Deleting Using .delete()
Function
We consider the same array and try to delete all instances of 3 again.
np.delete(arr, np.argwhere(arr==3))
In this case, .argwhere()
finds all the indices where 3 is present and .delete()
deletes the element at that place.
We can use just the .delete()
to delete elements at a particular index. Example:
np.delete(arr, 2)
This will delete the element at 2nd index of our array, i.e., 3.
That is a lot of information for one blog. I will write out a part 3 very soon where we will discuss the different methods for filling up arrays and how to make multiple arrays interact with each other. Till then, you can check out our YouTube video on Part 1 of NumPy:
https://youtu.be/u-yn7np77XM
Cya!
Top comments (0)