All you should know about Python Numpy 1D Arrays
In this article, we are going to discuss about one dimensional numpy arrays.
Most of you might know it, but I wanted to share my learning here.
Let’s get started.
What is an array?
We can say that array is a data structure which stores data of similar data type.
One Dimensional Array is nothing but a list having only one row without columns
Wait, what?
You may think that we do have Lists in Python which will store different kinds of data. Then why use arrays?
Well, We will cover that going forward.
Firstly, let’s jump into our topic.
How to create arrays in Python?
Python provides us with the best library numpy to work with arrays. We need to install numpy library before we start using it.
Installation:
pip install numpy
Creating numpy arrays:
Numpy arrays are created from lists.
import numpy as np
list1 = [1,2,3,4,5]
arr1 = np.array(list1)
arr1
In the above code,
import numpy as np: imports the numpy module
np.array(list1): creates an array from list1
Why Use Numpy Arrays?
The main reason for using arrays is that their execution speed. Arrays are more faster when compared to lists.
Speaking of lists, we cannot perform arithmetic operations on elements from two lists. Of course, we can do. But we need to iterate through each and every element in the list.
Array make this easy. Wondering how? Look at the following code.
import numpy as np
arr1 = np.array([1,2,3,5])
arr2 = np.array([6,7,9,1])
print(arr1 + arr2)
print(arr1 * arr2)
print(arr1/arr2)
print(arr1 ** arr2)
output:
[ 7 9 12 6]
[ 6 14 27 5]
[0.16666667 0.28571429 0.33333333 5. ]
[ 1 128 19683 5]
That’s how arrays make it easy.
Numpy is a major part of Data Science
Accessing array elements:
This part is similar to that of lists. We will provide the index of the element which we want to access.
array[index]
There is a lot more to know about 1D arrays. I had given a clear explanation with code in my notebook linked with my Github repo. You can check them out.
If you find this helpful, please leave a 👏🏻 and drop your views in the comments.
You can always reach me out on Linked In | Twitter | Instagram | Youtube
Happy Learning :)