Array’s are the foundation for all data science in Python. Arrays can be multidimensional, and all elements in an array need to be of the same type, all integers or all floats, for example.
In Python, you can create new datatypes, called arrays using the NumPy package. NumPy arrays are optimized for numerical analyses and contain only a single data type.
You first import NumPy and then use the array()
function to create an array. The array()
function takes a list as an input.
The type of my_array
is a numpy.ndarray
.
In the below example, you will convert a list to an array using the array()
function from NumPy. You will create a list a_list
comprising of integers. Then, using the array()
function, convert it an array.
In the below example, you add two numpy arrays. The result is an element-wise sum of both the arrays.
You can select a specific index element of an array using indexing notation.
You can also slice a range of elements using the slicing notation specifying a range of indices.
In the below example, you will import numpy
using the alias np
. Create prices_array
and earnings_array
arrays from the lists prices
and earnings
, respectively. Finally, print both the arrays.
When you run the above code, it produces the following result:
[170.12 93.29 55.28 145.3 171.81 59.5 100.5 ]
[ 9.2 5.31 2.41 5.91 15.42 2.51 6.79]
To learn more about NumPy arrays in Python
#python #developer