NumPy Basics
Your First Steps with Powerful Arrays
If you've spent any time with Python for data science, you've likely heard of NumPy. It's the foundational library for numerical computing, but what makes it so special? The short answer is speed and simplicity. NumPy gives us the
ndarray—a powerful and fast N-dimensional array object that is far more efficient than a standard Python list for numerical operations.Why not just use lists?
Let's look at a simple example. Say you want to add 2 to every number in a list. With Python lists, you'd need a loop.
With NumPy, it's as simple as writing it out. NumPy knows you want to perform the operation on every element.
This is called vectorization, and it's what makes NumPy so fast.
Creating Your First NumPy Arrays
Creating an array is straightforward. You can create a 1D array from a list or a 2D array from a list of lists.
From a Python List:
Using Built-in Functions:
NumPy also has functions for generating arrays quickly.
NumPy also has functions for generating arrays quickly.
np.zeros(): Creates an array filled with zeros.np.ones(): Creates an array filled with ones.np.arange(): Creates a sequence of numbers (similar to Python'srange).
Indexing and Slicing
Accessing elements in a NumPy array works just like with Python lists, but with extra power for multi-dimensional arrays.
Notice how we use a comma to separate the row and column indices.
Comments
Post a Comment