Menu

Getting Started with NumPy

Getting Started with NumPy

NumPy is the base library for fast number work in Python. This topic shows you how to create arrays, pick values from them, and do quick math on large sets of numbers.

a. What Is NumPy and Why It Matters

NumPy stands for Numerical Python. It is a library built for fast math on large groups of numbers. It is the foundation for Pandas, Matplotlib, and many machine learning tools.

Python lists can store numbers, but they are slow for heavy calculations. NumPy uses a special structure called an array, which is stored efficiently in memory. This makes operations many times faster.

NumPy also lets you do math on a whole array at once without writing loops. This style is called vectorization. It makes your code shorter and quicker.

b. Creating NumPy Arrays

You first import the library, usually with the short name np. Then you can create an array from a normal list.

import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr)

NumPy has helpful functions to create arrays quickly. np.zeros(5) makes an array of zeros, np.ones(5) makes an array of ones, and np.arange(0, 10, 2) creates a range of numbers with a step.

You can also build two-dimensional arrays, which look like tables with rows and columns. Use arr.shape to see the size and arr.dtype to see the data type. These checks are useful when debugging.

c. Indexing and Slicing Arrays

Indexing in NumPy works like it does in lists. You use square brackets and the position number. The first item is at index 0.

arr = np.array([10, 20, 30, 40, 50])
print(arr[1])
print(arr[1:4])

Slicing lets you pick a range of values. In the example above, arr[1:4] returns the items from index 1 up to, but not including, index 4. You can also use negative numbers to count from the end.

For two-dimensional arrays, you give the row and column like arr[0, 2]. You can also filter with conditions, such as arr[arr > 20], which returns only the values greater than 20.

d. Basic Mathematical Operations

NumPy lets you do math on full arrays in one step. Adding, subtracting, multiplying, or dividing an array by a number applies it to every item.

prices = np.array([100, 200, 300])
print(prices * 1.18)

You can also combine two arrays of the same size. The operation happens item by item. This is very useful for tasks like calculating total cost from price and quantity arrays.

NumPy also offers summary functions like np.sum(), np.mean(), np.min(), np.max(), and np.std(). These give you quick facts about your data. You will use similar functions in Pandas later.


Data Analysis with Python Handbook

WR

Wesline Rinisha



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details