Basic of Numphy
Basic of Numphy
Introduction to Numpy
Def:
● NumPy, short for Numerical Python, is a powerful Python library for numerical
computations.
● It's widely used in scientific computing, data analysis, machine learning, and
engineering because of its ability to efficiently process large, multi-dimensional
arrays and matrices.
● NumPy provides an extensive collection of mathematical functions to operate on
these arrays, making complex calculations much faster and more concise than using
pure Python.
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.
● NumPy is a Python library and is written partially in Python, but
most of the parts that require fast computation are written in C or
C++.
Installation of numpy
● pip install numpy.
● import numpy
● import numpy
print(arr)
● NumPy is usually imported under the ’np’ alias
● In python alias are an alternate name for referring to the same
thing
● Checking numpy version
Checking numpy version
import numpy as np
print(np.__version__)
o/p:
1.26.4
Create a NumPy ndarray Object
● NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
● We can create a NumPy ndarray object by using the array() function
● import numpy as np
● arr = np.array([1, 2, 3, 4, 5])
● print(arr)
● print(type(arr))Tr
[1 2 3 4 5] <class 'numpy.ndarray'>
y it
import numpy as np
# From a list
arr_from_list = np.array([1, 2, 3, 4, 5])
# From a tuple
arr_from_tuple = np.array((1, 2, 3, 4, 5))
print("Array from list:", arr_from_list)
print("Array from tuple:", arr_from_tuple)
o/p:
Array from list: [1 2 3 4 5]
Array from tuple: [1 2 3 4 5]
# Using arange
arr_arange = np.arange(5) # Array from 0 to 4
# Using linspace
arr_linspace = np.linspace(0, 1, 5) # 5 evenly spaced
values from 0 to 1
# Using random
arr_random = np.random.rand(5) # Array of 5 random floats
between 0 and 1
print("Array from list:", arr)
print("Array with arange:", arr_arange)
print("Array with linspace:", arr_linspace)
Array from list: [1 2 3 4 5]
print("Array
Array with arange:of
[0 random
1 2 3 4] floats:", arr_random)
Array with linspace: [0. 0.25 0.5 0.75 1. ]
Array of random floats: [0.75762723 0.21806401 0.08906999 0.5627405
0.85459441]
2. Reshaping of an Array
Aggregate operations compute a single value from an array, like sum, mean, max, min,
etc.
● Indexing allows accessing individual elements. NumPy uses zero-based indexing, just
like Python lists.
arr = np.array([10, 20, 30, 40, 50])
# Access elements
first_element = arr[0]
last_element = arr[-1]
print("First element:", first_element)
print("Last element:", last_element)
● Slicing lets you extract subarrays. Use the colon `:` to specify start, stop, and step.