Numpy-Arrays-In-Detail

NumPy — Numerical Python Numpy Arrays In Detail: A Beginner's Guide

By Champak RoyLearning Sutras · Varanasi

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

pip install numpy

Importing NumPy

import numpy as np

Creating NumPy Arrays

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

Zeros, Ones and Random Arrays

import numpy as np
a = np.zeros(5)
b = np.zeros((3,2))
c = np.ones(5)
d = np.ones((3,2))
e = np.random.random(5)
f = np.random.rand(3,2)
g = np.random.randn(3,2)

Useful Array Attributes

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a.shape)
print(a.ndim)
print(a.dtype)
print(a.size)
print(a.itemsize)
print(a.strides)
print(a.T)
(2, 3)
2
int64
6
8
(24, 8)
[[1 4]
[2 5]
[3 6]]

Reshaping Arrays

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)
e = a.reshape(-1,5)

Arithmetic and Matrix Operations

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
c = a + b
d = a - b
e = a * b
f = a / b
g = a * 2
h = a + 3
i = np.dot(a, b)

Solving Linear Equations

import numpy as np
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])
x = 1.0
y = 1.0

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 (Practice)

  1. Function to create zeros array → np.zeros()
  2. Attribute for number of dimensions → .ndim
  3. Matrix product → np.dot(a,b) or a @ b

0 Comments

Post a Comment

0 Comments