NumPy is a Python library.
NumPy is used for working with arrays.
NumPy is short for "Numerical Python".
The array object in NumPy is called ndarray, it provides a lot of supporting methods that make working with array very easy.
Why is NumPy Faster Than Lists?
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.
This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU architectures.
**We can create a NumPy ndarray object by using the array() function.**
#To create an ndarray, we can pass a list into the array() method, and it will be converted into an ndarray:
import numpy as np
mylist = [1, 2, 3, 4, 5]
arr = np.array(mylist)
print(mylist) #[1, 2, 3, 4, 5]
print(arr) #[1 2 3 4 5]
print(arr.sum()) #15
print(np.__version__) #1.23.5
print(type(arr)) # <class 'numpy.ndarray'>
Dimensions in Arrays
# 0-D Arrays: 0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
arr = np.array(42)
print(arr) # 42
# 1-D Arrays
arr = np.array([1, 2, 3, 4, 5])
print(arr) # [1, 2, 3, 4, 5]
# 2-D Arrays
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr) # [[1 2 3]
[4 5 6]]
# 3-D arrays
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr) # [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]
# Check how many dimensions the arrays have:
a = np.array(42)
print(a.ndim) # 0
# Higher Dimensional Arrays: When the array is created, you can define the number of dimensions by using the ndmin argument.
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr) # [[[[[1 2 3 4]]]]]
print('number of dimensions :', arr.ndim) # 5
# Shape
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape) # (2,4)
# The example above returns (2, 4), which means that the array has 2 dimensions, where the first dimension has 2 elements and the second has 4.
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)
# [
[
[
[
[1 2 3 4]
]
]
]
]
# shape of array : (1, 1, 1, 1, 4)
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3) # row*column
newarr
# array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4,3,1) # means 4 dimensional and each dimensional have 3*1
# 4*1=>1=>3*1
print(newarr)
#
[
[
[ 1]
[ 2]
[ 3]
]
[
[ 4]
[ 5]
[ 6]
]
[
[ 7]
[ 8]
[ 9]
]
[
[10]
[11]
[12]
]
]