NumPy Basics

Chapter 10 • Python
4
7
2
7
6
4
9
9
2
9
9
2
8
2
5
9
[ ]
Chapter 10 • Python

NumPy Basics

Numerical Python — Arrays, Operations, Dimensions, Slicing और बहुत कुछ! Python की सबसे powerful scientific computing library को मास्टर करें।

N-D Arrays
Dimensions
Slicing
Reshape
Operations

Introduction — NumPy क्या है? →

Numpy का full form Numerical Python है। 2005 में developer Travis Oliphant ने open source project के रूप में Numpy library को develop किया।

📝 Numpy Python की सबसे important library है जो scientific computing के लिए fundamental package provide करती है!
Scientific Computing

Fundamental Package

Complex mathematical functions aur C/C++ language ko use karta hai

N-Dimensional Arrays

Core Feature

N-dimensional array object aur multi-dimensional data support

🔑 Key Points:

  • Numpy ek Python library hai jo complex mathematical functions ko support karta hai
  • Ye C aur C++ language ko internally use karta hai (isliye fast hai)
  • Python ki scientific computing ke liye fundamental package hai
  • N-dimensional array object aur object array provide karta hai

Why use NumPy? →

Numpy ka use array ke saath work karne ke liye kiya jata hai। Python me natively array concept nahi hota — issi liye Numpy ka main purpose array object provide karna hai।

💡 Traditional Python lists 50x slower hain as compared to Numpy arrays! Numpy internally C me compiled hai isliye ye bahut fast hai।
50x Faster

Python list se 50 guna fast operations

N-D Arrays

Multi-dimensional array support

Scientific

Scientific computing ke liye perfect

FeaturePython ListNumPy Array
Speed❌ Slow✅ 50x Faster
Memory❌ Zyada use✅ Kam use
N-D Support❌ Nahi✅ N-Dimensional
Math Functions❌ Limited✅ Complete
Scientific Use❌ Not ideal✅ Perfect

NumPy Installation →

Numpy install karne ke liye aapke system me PIP (Python Package Installer) install hona chahiye।

📝 PIP Python ke saath automatically install hota hai (Python 3.4+ versions me)। Agar nahi hai to python -m ensurepip run karein।
Installation Command
python
pip install numpy
💡 Agar aap Anaconda use kar rahe ho to NumPy already installed hota hai! Check karne ke liye: pip show numpy

Import NumPy →

Successfully install hone ke baad hum is package ko module ki tarah use kar sakte hain। Convention ke according NumPy ko np alias se import karte hain।

python
import numpy as np

# Ab hum np ka use karke NumPy ke functions access kar sakte hain
print(np.__version__)    # NumPy version check
💡 np ek standard alias hai jo sabhi Python developers use karte hain। Ye code ko short aur readable banata hai!

Creating NumPy Array →

Numpy ka use karke array ko teen tarike se bana sakte hain:

1
array()

List/Tuple se array banao

2
arange()

Start, stop, step se array

3
linspace()

Fixed elements ka array

(i) array() FunctionList ya Tuple se array banao

Array function ka use karke array banaya jata hai। Ye ek argument input ke roop me leta hai — list ya tuple

Syntax
<array_name> = numpy_obj.array(<list, tuple>)
Example — Array from List
python
import numpy as np

a = [23, 45, 56, 75, 98]
print(type(a))          # <class 'list'>

b = np.array(a)
print(type(b))          # <class 'numpy.ndarray'>
print(b)                # [23 45 56 75 98]
Output
<class 'list'>
<class 'numpy.ndarray'>
[23 45 56 75 98]
📘 Question — Count Age (Major & Minor)

Ek program likho jo ages ki list me se major (≥18) aur minor (<18) count kare।

python
import numpy as np

m = n = 0
a = [17, 15, 20, 25, 40, 55]
print(type(a))

b = np.array(a)
print(type(b))

for i in b:
    if(i >= 18):
        m = m + 1
    else:
        n = n + 1

print("Major:", m)
print("Minor:", n)
Output
<class 'list'>
<class 'numpy.ndarray'>
Major: 4
Minor: 2
(ii) arange() FunctionSequence values ka array banao

Ye function value ko array me return karta hai। Ye teen arguments leta hai: start, stop, step

Syntax
<array_name> = numpy_obj.arange([start], [stop], [step])
Example — arange() Forward
python
import numpy as np

h = np.arange(1, 10, 2)
print(h)    # [1 3 5 7 9]
Output
[1 3 5 7 9]
Example — arange() Reverse
python
import numpy as np

h = np.arange(20, 3, -2)
print(h)    # [20 18 16 14 12 10  8  6  4]
Output
[20 18 16 14 12 10  8  6  4]
(iii) linspace() FunctionStart aur Stop ke beech fixed elements

Ye function array start aur stop ke beech fixed number of elements return karta hai evenly spaced।

Syntax
<array_name> = numpy_obj.linspace(start, stop, num, endpoint=True, retstep=False)
ParameterDescription
startStarting value
stopLast value
numTotal elements (default = 50)
endpointEnd point include hoga ya nahi (default True)
retstepStep value return karega ya nahi (default False)
Example — linspace() Basic
python
import numpy as np

a = np.linspace(1, 5, 10)
print(a)
Output
[1.         1.44444444 1.88888889 2.33333333 2.77777778 3.22222222
 3.66666667 4.11111111 4.55555556 5.        ]
Example — linspace() with retstep
python
import numpy as np

a = np.linspace(1, 5, 10, endpoint=True, retstep=True)
print(a)
Output
(array([1.        , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
       3.22222222, 3.66666667, 4.11111111, 4.55555556, 5.        ]), 0.4444444444444444)
📝 Jab retstep=True hota hai to output me array ke saath step value bhi return hoti hai!

Dimensions of Array →

Numpy me multi dimensional array ban sakta hai। ndim function se array ki dimension pata chalti hai।

Syntax
numpy_obj.ndim(<array_name>)
0D
Zero Dimensional

Single element array (scalar)

np.array(42)
1D
One Dimensional

List type — ek row

np.array([1,2,3])
2D+
Multi Dimensional

Nested lists — rows & columns

np.array([[1,2],[3,4]])
Example — 1D Array Dimension
python
import numpy as np

a = np.array([23, 45, 78])
print(a)
print("Dimension:", np.ndim(a))
Output
[23 45 78]
Dimension: 1
Example — Multi Dimensional Arrays

Nested lists ka use karke 2D aur 3D arrays banaye ja sakte hain:

python
import numpy as np

# 1D Array
a = np.array([12, 5])
print("1D:", a, "→ dim:", np.ndim(a))

# 2D Array
b = np.array([[4, 6], [7, 8]])
print("2D:", b, "→ dim:", np.ndim(b))

# 3D Array
c = np.array([[[4, 7], [6, 9]], [[5, 8], [7, 10]]])
print("3D:", c, "→ dim:", np.ndim(c))
Output
1D: [12  5] → dim: 1
2D: [[4 6]
 [7 8]] → dim: 2
3D: [[[ 4  7]
  [ 6  9]]
 [[ 5  8]
  [ 7 10]]] → dim: 3

📊 Array Dimensions Visualization

0D (Scalar)

42

1D (Vector)

1
2
3

2D (Matrix)

1
2
3
4

Shape of Array →

Array ki shape indexes ka tuple hoti hai jo har dimension me elements ki sankhya batati hai।

Syntax
array_obj.shape    # OR    np.shape(array_name)
Example — Array Shape
python
import numpy as np

a = np.array([[4, 5, 6], [7, 8, 9]])
print(a)
print("Shape (function):", np.shape(a))
print("Shape (attribute):", a.shape)
Output
[[4 5 6]
 [7 8 9]]
Shape (function): (2, 3)
Shape (attribute): (2, 3)
📝 (2, 3) ka matlab hai — 2 rows aur 3 columns!
Example — Shape Change

Array ki shape ko change bhi kiya ja sakta hai:

python
import numpy as np

a = np.array([[4, 5, 6], [7, 8, 9]])
print("Original shape:", a.shape)
print(a)

a.shape = (1, 6)
print("\nNew shape:", a.shape)
print(a)

a.shape = (3, 2)
print("\nAnother shape:", a.shape)
print(a)
Output
Original shape: (2, 3)
[[4 5 6]
 [7 8 9]]

New shape: (1, 6)
[[4 5 6 7 8 9]]

Another shape: (3, 2)
[[4 5]
 [6 7]
 [8 9]]

Array Indexing →

Array ke element ko access karne ke liye index use hota hai। Numpy me indexing 0 se start hoti hai।

Syntax
array_name[index]           # 1D
array_name[row][col]        # 2D
array_name[depth][row][col] # 3D
Example — 1D Array Indexing
python
import numpy as np

a = np.array([4, 7, 6])
print(a[0])    # 4
print(a[1])    # 7
print(a[2])    # 6
Output
4
7
6
Example — 2D Array Indexing
python
import numpy as np

a = np.array([[4, 7, 6], [7, 8, 4]])
print(a)

# Method 1: Double bracket
print(a[1][1])    # 8
print(a[0][2])    # 6

# Method 2: Comma separated
print(a[1, 1])    # 8
print(a[0, 2])    # 6
Output
[[4 7 6]
 [7 8 4]]
8
6
8
6
Example — 3D Array Indexing
python
import numpy as np

a = np.array([[[2, 3], [5, 6]], [[6, 9], [7, 3]]])
print(a)
print("Shape:", a.shape)

print(a[0][0][1])    # 3
print(a[1][0][0])    # 6
print(a[1][1][1])    # 3
Output
[[[2 3]
  [5 6]]

 [[6 9]
  [7 3]]]
Shape: (2, 2, 2)
3
6
3

🎯 Indexing Visual — 2D Array

Row 0 →
4[0,0]
7[0,1]
6[0,2]
Row 1 →
7[1,0]
8[1,1]
4[1,2]

Array Slicing →

Slicing se array ka ek part (subset) nikala ja sakta hai। Ye Python list slicing jaisa hi hai but multi-dimensional support ke saath।

1D Array SlicingSingle dimension array ka slice
Syntax
array_name[start:stop:step]
Example — 1D Slicing
python
import numpy as np

a = np.array([3, 5, 7, 8, 4, 6, 2])

print(a[3:6])      # [8 4 6]
print(a[0:7:2])    # [3 7 4 2]
print(a[::-1])     # [2 6 4 8 7 5 3] — reversed
print(a[:])        # [3 5 7 8 4 6 2] — full array
print(a[3:])       # [8 4 6 2] — index 3 se end tak
Output
[8 4 6]
[3 7 4 2]
[2 6 4 8 7 5 3]
[3 5 7 8 4 6 2]
[8 4 6 2]
2D Array SlicingRows aur columns dono ka slice
Syntax
array_name[row_start:row_stop:step, col_start:col_stop:step]
Example — 2D Slicing
python
import numpy as np

a = np.array([[2, 3, 5, 6], [3, 4, 6, 8], [5, 7, 2, 9]])
print(a)
print()

print("Row 2 to 3:")
print(a[2:3])          # [[5 7 2 9]]

print("\nColumn 2 (all rows):")
print(a[:, 2])         # [5 6 2]

print("\nRows 0-2, Cols 1-2:")
print(a[0:3, 1:3])     # [[3 5] [4 6] [7 2]]
Output
[[2 3 5 6]
 [3 4 6 8]
 [5 7 2 9]]

Row 2 to 3:
[[5 7 2 9]]

Column 2 (all rows):
[5 6 2]

Rows 0-2, Cols 1-2:
[[3 5]
 [4 6]
 [7 2]]
3D Array SlicingDepth, rows aur columns ka slice
Syntax
array_name[depth_start:stop, row_start:stop, col_start:stop]
Example — 3D Slicing
python
import numpy as np

a = np.array([[[4, 3, 5], [6, 7, 1]], [[8, 9, 1], [6, 7, 8]]])
print("Shape:", a.shape)
print(a)

print("\nSlice [1:2, 0:2, 1:3]:")
print(a[1:2, 0:2, 1:3])
Output
Shape: (2, 2, 3)
[[[4 3 5]
  [6 7 1]]

 [[8 9 1]
  [6 7 8]]]

Slice [1:2, 0:2, 1:3]:
[[[9 1]
  [7 8]]]

Reshape →

Array ki shape change karne ke liye reshape() function ka use hota hai। Total elements same rehne chahiye!

Syntax
array_name.reshape(rows, columns)
⚠️ Reshape tabhi kaam karega jab total elements = rows × columns। Warna error aayega!
Example — Reshape
python
import numpy as np

a = np.array([1, 2, 3, 4, 5, 6])
print("Original:", a)
print("Shape:", a.shape)

b = a.reshape(3, 2)
print("\nReshaped (3x2):")
print(b)

c = a.reshape(2, 3)
print("\nReshaped (2x3):")
print(c)
Output
Original: [1 2 3 4 5 6]
Shape: (6,)

Reshaped (3x2):
[[1 2]
 [3 4]
 [5 6]]

Reshaped (2x3):
[[1 2 3]
 [4 5 6]]

Ones, Zeros, Ones_like & Zeros_like →

ones()Array ko 1 se bharta hai
Syntax
numpy_obj.ones((size), dtype=int/float)
Example — ones()
python
import numpy as np

a = np.ones((3, 5), dtype=int)
print(a)
Output
[[1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]]
zeros()Array ko 0 se bharta hai
Syntax
numpy_obj.zeros((size), dtype=int/float)
Example — zeros()
python
import numpy as np

a = np.zeros((5, 6), dtype=int)
print(a)
Output
[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]
ones_like()Existing array jaisa shape ka ones array
Syntax
numpy_obj.ones_like(array, dtype=int/float)
Example — ones_like()
python
import numpy as np

b = np.array([2, 4, 5, 6, 7])
a = np.ones_like(b, dtype=int)
print("Original:", b)
print("Ones_like:", a)
Output
Original: [2 4 5 6 7]
Ones_like: [1 1 1 1 1]
zeros_like()Existing array jaisa shape ka zeros array
Syntax
numpy_obj.zeros_like(array, dtype=int/float)
Example — zeros_like()
python
import numpy as np

b = np.array([[2, 4], [5, 6]])
a = np.zeros_like(b, dtype=int)
print("Original:")
print(b)
print("Zeros_like:")
print(a)
Output
Original:
[[2 4]
 [5 6]]
Zeros_like:
[[0 0]
 [0 0]]

Empty & Copy →

empty()Uninitialized array banata hai (random values)
Syntax
numpy_obj.empty((size), dtype=int/float)
Example — empty()

Empty function array banata hai but usmein random (garbage) values hoti hain — ye initialized nahi hota!

python
import numpy as np

a = np.empty((4, 4), dtype=int)
print(a)
Output
[[ 0  0  0  0]
 [ 0  0  0  0]
 [ 0  0  0  0]
 [ 0  0  0  0]]
⚠️ Empty array me values random ho sakti hain! Ye guaranteed zero nahi hota — sirf memory allocate karta hai।
copy()Array ki deep copy banata hai
Syntax
b = a.copy()
Example — copy()

Copy se ek independent copy banti hai — original me change karne par copy pe asar nahi hota।

python
import numpy as np

a = np.array([3, 4, 6])
b = a.copy()

print("Original:", a)
print("Copy:", b)

# Original me change karo
a[0] = 99
print("\nAfter changing original:")
print("Original:", a)
print("Copy:", b)    # copy unchanged!
Output
Original: [3 4 6]
Copy: [3 4 6]

After changing original:
Original: [99  4  6]
Copy: [3 4 6]
💡 Copy ke bina agar b = a karte ho to dono same array point karte hain — ek me change = dono me change!

Identity & Eye →

identity()Identity matrix return karta hai (diagonal pe 1)

Identity matrix me diagonal elements 1 hote hain aur baaki sab 0 hote hain। Ye hamesha square matrix hoti hai।

Syntax
numpy_obj.identity(size, dtype=int/float)
Example — identity()
python
import numpy as np

a = np.identity(4, dtype=int)
print(a)
Output
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
eye()Diagonal position change kar sakte ho

Eye function identity matrix jaisi hai but isme rows ≠ columns ho sakti hain aur diagonal position (k) change kar sakte ho।

Syntax
numpy_obj.eye(rows, cols, k=0, dtype=int/float)
ParameterDescription
rNumber of rows
cNumber of columns
kDiagonal position (0=main, +ve=upper, -ve=lower)
Example — eye() with different k values
python
import numpy as np

# Default diagonal (k=0)
a = np.eye(4, 5, 0, dtype=int)
print("k=0 (main diagonal):")
print(a)

# Upper diagonal (k=1)
b = np.eye(4, 5, 1, dtype=int)
print("\nk=1 (upper diagonal):")
print(b)

# Lower diagonal (k=-2)
c = np.eye(4, 5, -2, dtype=int)
print("\nk=-2 (lower diagonal):")
print(c)
Output
k=0 (main diagonal):
[[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]]

k=1 (upper diagonal):
[[0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]

k=-2 (lower diagonal):
[[0 0 0 0 0]
 [0 0 0 0 0]
 [1 0 0 0 0]
 [0 1 0 0 0]]
Featureidentity()eye()
ShapeHamesha square (n×n)Rectangular bhi ho sakta hai (r×c)
DiagonalHamesha main diagonalk se diagonal shift kar sakte ho
FlexibilityKam flexibleZyada flexible

Practice Questions →

In programs ko khud likhne ka prayaas karein — Chapter 10 ko aur acche se samajhne ke liye 💪

Q1
Write a program to create a 1D NumPy array from a list and print its type.
Q2
Write a program to create arrays using array(), arange(), and linspace() — compare their outputs.
Q3
Write a program to find the dimension and shape of a 3D array.
Q4
Create a 2D array and access specific elements using indexing.
Q5
Write a program to slice a 2D array — get specific rows, columns and sub-matrix.
Q6
Write a program to reshape a 1D array of 12 elements into 3×4, 4×3, 2×6 and 6×2 arrays.
Q7
Create a 3×3 ones matrix and a 4×4 zeros matrix with integer dtype.
Q8
Write a program using ones_like() and zeros_like() with a given array.
Q9
Create an identity matrix of size 5 and an eye matrix with k=-1.
Q10
Write a program to demonstrate the difference between copy and view (assignment).
Q11
Create a NumPy array and reverse it using slicing.
Q12
Write a program to count even and odd numbers in a NumPy array.
Q13
Create a 3D array and extract a 2D slice from it.
Q14
Write a program to create an array using linspace with retstep=True and print the step value.
Q15
Create a program that demonstrates empty() — show that values are random/garbage.

Chapter 10 — Key Points :

  • NumPy — Numerical Python, Travis Oliphant (2005)
  • 50x Faster — Python list se 50 guna fast
  • 3 Array Creation: array(), arange(), linspace()
  • Dimensions: 0D (scalar), 1D (vector), 2D (matrix), 3D+
  • Shape: array.shape se rows × columns pata chalta hai
  • Indexing: a[0], a[row,col], a[depth,row,col]
  • Slicing: a[start:stop:step] — 1D, 2D, 3D support
  • Utility: ones, zeros, empty, copy, identity, eye, reshape
Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.