NumPy is an open-source library that provides powerful and easy-to-use tools for numerical computing and data manipulation in Python. It is built on top of the C programming language and is widely used in scientific computing, data analysis, and machine learning tasks.
The first step in working with NumPy is to install it using pip or conda and import it into your code.
!pip install numpy import numpy as np
One of the most commonly used data structures in NumPy is the ndarray. An ndarray is a multi-dimensional array that can hold data of the same type (e.g. numbers, strings, dates). You can create an ndarray from a list or a tuple. For example:
data = [1, 2, 3, 4, 5] arr = np.array(data) print(arr) # [1 2 3 4 5]
Once you have an ndarray, you can use various functions to manipulate and analyze the data. For example, you can use the shape attribute to see the dimensions of an ndarray:
print(arr.shape) # (5,)
You can use the ndim attribute to see the number of dimensions of an ndarray.
print(arr.ndim) # 1
You can use the dtype attribute to see the data type of an ndarray.
print(arr.dtype) # int64
You can also perform mathematical operations on an ndarray. For example, you can use the sum() function to calculate the sum of all elements in an ndarray:
print(arr.sum()) # 15
You can use the mean() function to calculate the mean of all elements in an ndarray:
print(arr.mean()) # 3.0
In addition , NumPy provides various other functions such as reshaping, slicing, indexing and broadcasting of arrays, which are useful for data manipulation and analysis. For example, you can use the reshape() function to change the shape of an ndarray:
arr = arr.reshape(5,1) print(arr) # [[1] # [2] # [3] # [4] # [5]]
You can use the slicing and indexing to access specific elements of an ndarray:
print(arr[1]) # 2
You can also use the np.zeros() and np.ones() function to create an array of zeros or ones:
ones = np.ones((3,3)) print(ones) # [[1. 1. 1.] # [1. 1. 1.] # [1. 1. 1.]]
In conclusion, the NumPy library in Python provides a wide range of powerful and easy-to-use tools for numerical computing and data manipulation. The ndarray data structure is powerful and efficient, and the library also provides various functions for manipulating and analyzing data. With consistent practice, you will become comfortable with these tools and will be able to implement them in your code with ease.
Hope you liked this post 🙂