Beginning Numpy

NumPy — Numerical Python: A Beginner's Guide

Introduction

NumPy (Numerical Python) is the fundamental Python package for scientific computing. It provides efficient multi-dimensional arrays (ndarrays), mathematical functions, linear algebra routines, random number generators and more. In this post we will cover the basics — installation, creating arrays, attributes, reshaping, arithmetic operations, and solving linear systems with np.linalg.

Keywords

NumPy, ndarray, numpy.array, reshape, np.linalg, vectorized operations

Why NumPy matters

  • Performance: NumPy arrays are implemented in C — much faster than Python lists.
  • Memory efficient: compact representation of numeric data.
  • Foundation: Many data science & ML libraries (Pandas, Scikit-learn, TensorFlow) build on NumPy.
  • Convenience: vectorized operations avoid explicit Python loops.
Learning Sutras — Champak Roy
Short, practical lessons for students and developers in Varanasi.

Installing NumPy

Install via pip:

pip install numpy

Importing NumPy

Standard import alias:

import numpy as np

Creating NumPy arrays

Use np.array() to create arrays from Python lists.

One-dimensional array

import numpy as np
a = np.array([1, 2, 3])
print(a)
Output:
[1 2 3]

Two-dimensional array

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
Output:
[[1 2 3]
 [4 5 6]]

Generate zeros, ones, and random arrays

import numpy as np
# Zeros and ones
a = np.zeros(5)
b = np.zeros((3,2))
c = np.ones(5)
d = np.ones((3,2))

# Random arrays
e = np.random.random(5)   # uniform [0,1)
f = np.random.rand(3,2)   # same as above but shaped
g = np.random.randn(3,2)  # standard normal (Gaussian)

Useful array attributes

Common attributes that help understand array shape and storage:

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a.shape)    # (2, 3)
print(a.ndim)     # 2
print(a.dtype)    # e.g. int64
print(a.size)     # total elements
print(a.itemsize) # bytes per element
print(a.strides)  # byte-step for each dimension
print(a.T)        # transpose
Example Output (typical):
(2, 3)
2
int64
6
8
(24, 8)
[[1 4]
[2 5]
[3 6]]

Reshaping arrays

Use .reshape() to change dimensions without copying (if possible).

import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10])

b = a.reshape(5,2)
c = a.reshape(2,5,1)
d = a.reshape(2,-1)   # -1 means infer dimension
e = a.reshape(-1,5)
Example: Reshaped outputs
b:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
c:
[[[ 1]
[ 2]
[ 3]
[ 4]
[ 5]]
[[ 6]
[ 7]
[ 8]
[ 9]
[10]]
d and e produce similar shaped arrays depending on -1 inference.

Element-wise arithmetic & matrix operations

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

# Element-wise
c = a + b
d = a - b
e = a * b
f = a / b

# Scalar
g = a * 2
h = a + 3

# Matrix multiplication (dot product)
i = np.dot(a, b)   # or a @ b
Example Output
a + b: [[ 6 8]
[10 12]]
a * b: [[ 5 12]
[21 32]]
a dot b: [[19 22]
[43 50]]

Solving simultaneous linear equations with np.linalg.solve

Example: solve

import numpy as np
# Solve:
# 2x + 1y = 3
# 1x + 1y = 2

A = np.array([[2, 1], [1, 1]])
b = np.array([3, 2])

x = np.linalg.solve(A, b)
print("x =", x[0])
print("y =", x[1])
Output:
x = 1.0
y = 1.0

Explanation / Dry run

  1. We define matrix A as coefficients of variables (rows = equations).
  2. We define vector b as constants (right-hand side).
  3. np.linalg.solve(A, b) computes the solution x so that A @ x = b.
  4. This generalizes to n × n coefficient matrices and n-length vectors.

Complexity and notes

  • Most NumPy operations are implemented in optimized C loops — they are vectorized and usually O(n) per element for element-wise ops.
  • Matrix multiplication and some linear-algebra routines may have higher complexity (e.g. O(n³) for naive dense matrix solve), but NumPy delegates to optimized BLAS/LAPACK when available.
  • Be careful with data types; mixed types can cause upcasting (e.g. int → float).

Mini project — Matrix statistics

import numpy as np
matrix = np.random.randint(1, 100, (5, 5))

print("Matrix:\\n", matrix)
print("Mean:", np.mean(matrix))
print("Row-wise Mean:", np.mean(matrix, axis=1))
print("Column-wise Mean:", np.mean(matrix, axis=0))

Quick MCQs (for practice)

  1. What function creates an array of zeros?
    Answer: np.zeros()
  2. Which attribute gives the number of dimensions?
    Answer: .ndim
  3. How do you compute matrix product?
    Answer: np.dot(a, b) or a @ b

0 Comments

Post a Comment

0 Comments