NumPy is a powerful Python library for numerical computing, particularly when working with arrays and matrices. It provides a wide range of built-in functions that operate on NumPy arrays.
1. numpy.array()
:
- Creates an array from a Python list or tuple.
- It allows specifying the data type explicitly or inferring it based on the input elements.
import numpy as np
a = np.array([1, 2, 3])
print(a)
OUTPUT
[1 2 3]
2.Indexing and Slicing:
To access specific elements or ranges within an array, you can use indexing and slicing. Slicing creates a new view of the original array, allowing you to modify the content.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1]) # Access element at row 0, column 1
print(arr[:, 1]) # Access all elements in column 1
OUTPUT
2
[2, 5]
3. numpy.transpose()
:
Swaps the axes of a given array, effectively transposing rows and columns.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.transpose(a)
print("\nTransposed array:")
print(b)
OUTPUT
Transposed array:
[[1 4]
[2 5]
[3 6]]
4. np.reshape()
The np.reshape()
function in NumPy is used to give a new shape to an array without changing its data. It allows you to rearrange the elements of the array into a new shape specified by the argument.
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
# Reshape the array into a 2x3 array
b = np.reshape(a, (2, 3))
print(b)
OUTPUT
[[1 2 3]
[4 5 6]]
5. np.add()
The np.add()
function in NumPy is used to perform element-wise addition between two arrays or between an array and a scalar value. It computes the sum of corresponding elements in the input arrays. If the inputs have different shapes, they must be broadcastable to a common shape.
import numpy as np
# Create two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Perform element-wise addition
result = np.add(a, b)
print(result)
OUTPUT
[5 7 9]