Introduction to NumPy
What is NumPy?
NumPy is a powerful, open-source Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. Widely used in data science, machine learning, and scientific research, NumPy is a cornerstone of Python's numerical ecosystem.
Installing NumPy
To install NumPy, use pip, the Python package manager. Run the following command in your terminal or command prompt:
pip install numpy
Ensure you have Python installed. You can verify the installation by checking the version in Python:
import numpy print(numpy.__version__)
Importing NumPy
Once installed, import NumPy into your Python script or notebook using the conventional alias 'np':
import numpy as np
This allows you to access NumPy's functions and classes with the 'np' prefix.
NumPy vs Python Lists
While Python lists are flexible and can hold mixed data types, NumPy arrays are more efficient for numerical operations. Key differences include:
- Performance: NumPy arrays are faster for mathematical operations due to optimized, compiled C code.
- Memory: NumPy uses less memory by storing elements of the same type contiguously.
- Functionality: NumPy offers vectorized operations, broadcasting, and advanced indexing, unlike lists.
Basic Array Creation (np.array)
Create a NumPy array using the np.array() function. Examples:
import numpy as np # 1D array arr1 = np.array([1, 2, 3, 4]) # 2D array arr2 = np.array([[1, 2], [3, 4]]) print(arr1) print(arr2)
Checking Data Types and Shapes
NumPy arrays have attributes to inspect their properties:
- Data Type (dtype): Check the type of elements with
arr.dtype. - Shape: Get the dimensions with
arr.shape.
import numpy as np arr = np.array([1, 2, 3, 4]) print(arr.dtype) # e.g., int64 print(arr.shape) # e.g., (4,)