NumPy operations in Python

NumPy Operations for Beginners

NumPy Operations for Beginners

Learn NumPy step by step with outputs


Python Logo

🧠 What is NumPy?

NumPy (short for Numerical Python) is a powerful open-source Python library used for scientific and mathematical computing.

It provides fast and efficient ways to work with arrays, matrices, and numerical operations.

It’s also the foundation of many data science and machine learning libraries like pandas, scikit-learn, and TensorFlow.

The main feature of NumPy is its ndarray (n-dimensional array), which is much more powerful and flexible than regular Python lists.

# Example: Create a simple NumPy array
import numpy as np
arr = np.array([1, 2, 3])
print(arr)

Output: [1 2 3]

✅ NumPy Basic Operations List

  • 1D Arraynp.array([1, 2, 3, 4, 5])
  • 2D Arraynp.array([[1, 2, 3], [4, 5, 6]])
  • Random Floatsnp.random.rand(2)
  • Random Integersnp.random.randint(1, 10)
  • Zeros Arraynp.zeros((2, 3))
  • Ones Arraynp.ones((2, 2))
  • Identity Matrixnp.eye(3)
  • Arange (Range Array)np.arange(1, 5)
  • Slicingarr[1:4]
  • Indexingarr[1, 0]
  • Linspacenp.linspace(0, 1, 5)

First, install NumPy:

pip install numpy

Import NumPy:

import numpy as np

1. 1D Array

A 1D array is a single row or list of elements stored in a linear sequence, where each element can be accessed using a single index.

arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)
[1 2 3 4 5]

2. 2D Array

A 2D array is a table-like structure with rows and columns, where each element is accessed using two indices — one for the row and one for the column.

arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2)
[[1 2 3]
[4 5 6]]

3. Random Floats

Random floats are decimal numbers generated unpredictably within a specified range, often between 0.0 and 1.0. They're commonly used in simulations, games, and statistical sampling.

rand_arr = np.random.rand(2, 3) # Create a 2x3 array of random floats between 0 and 1 print(rand_arr)
[[0.92604385 0.2201824 0.06113444
[0.08762701 0.2009916 0.14965612]] (changes every run)

4. Random Integers

Random integers are whole numbers generated unpredictably within a specified range. They’re often used in games, simulations, and randomized algorithms.

rand_ints = np.random.randint(1, 10, size=(2, 3)) # Create a 2x3 array of random integers between 1 and 9 print(rand_ints)
[[3 7 1]
[9 2 6]] (changes every run)

5. Zeros

Zeros are arrays filled entirely with the value 0, often used to initialize data structures or placeholders.

zeros_arr = np.zeros((2, 3)) # Create a 2x3 array filled with zeros print(zeros_arr)
[[0. 0. 0.]
[0. 0. 0.]]

6. Ones

Ones are arrays filled entirely with the value 1, commonly used for initializing weights or masks.

ones_arr = np.ones((2, 3)) # Create a 2x3 array filled with ones print(ones_arr)
[[1. 1. 1.]
[1. 1. 1.]]

7. Identity Matrix

An identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. It’s used in linear algebra and has many practical applications.

identity_mat = np.identity(3) # Create a 3x3 identity matrix print(identity_mat)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

8. Arange

Arange is a function that generates a sequence of numbers within a specified range. It’s often used for generating arrays of integers.

arr = np.arange(1, 10, 2) # Create an array starting at 1, up to (but not including) 10, step 2 print(arr)
[1 3 5 7 9]

9. Slicing

Slicing is a technique to extract a portion of an array, list, or string. It’s used to create sub-arrays or sub-strings.

arr = np.array([10, 20, 30, 40, 50]) slice_arr = arr[1:4] # Extract elements from index 1 to 3 print(slice_arr)
[20 30 40]

2D Slicing

2D slicing extracts specific rows and columns from a 2D array using row and column index ranges.

arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) slice_2d = arr2d[0:2, 1:3]
# Extract rows 0-1 and columns 1-2 print(slice_2d)
[[2 3]
[5 6]]

10. Indexing

Indexing is a technique to access individual elements of an array, list, or string using their position or index.

arr1d = np.array([10, 20, 30, 40])
print(arr1d[2]) # Access the 3rd element (index 2)
30

2D Indexing

2D indexing is used to access specific elements in a 2D array by specifying both row and column indices.

arr2d = np.array([[1, 2, 3], [4, 5, 6]]) print(arr2d[1, 2]) # Access the element at 2nd row, 3rd column (index [1, 2])
6

11. Linspace

Linspace generates a sequence of evenly spaced numbers within a specified range. It’s often used for creating arrays of fixed size.

arr = np.linspace(0, 1, 5) # Generate 5 evenly spaced values from 0 to 1 print(arr)
[0. 0.25 0.5 0.75 1. ]

📊 Summary Table

Operation Function Example Output (Example)
1D Arraynp.array([...])[1, 2, 3][1 2 3]
2D Arraynp.array([[...],[...]])[[1,2,3],[4,5,6]][[1 2 3]
[4 5 6]]
Random Floatsnp.random.rand()np.random.rand(2)[0.5 0.9]
Random Integersnp.random.randint()np.random.randint(1,10)5
Zerosnp.zeros()np.zeros((2,3))[[0. 0. 0.]
[0. 0. 0.]]
Onesnp.ones()np.ones((2,2))[[1. 1.]
[1. 1.]]
Identitynp.eye()np.eye(3)[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Arangenp.arange()np.arange(1,5)[1 2 3 4]
Slicingarr[start:end]arr[1:4][20 30 40]
Indexingarr[i], arr[i,j]arr[1,0]3
Linspacenp.linspace()np.linspace(0, 1, 5)[0. 0.25 0.5 0.75 1.]

📝 Practice The Questions

  1. Create a 1D NumPy array with values from 10 to 50.
  2. Create a 2D array with 3 rows and 4 columns filled with ones.
  3. Generate 5 random float numbers between 0 and 1 using np.random.rand().
  4. Generate a 3x3 matrix of random integers between 1 and 20.
  5. Create an array of 6 zeros and reshape it into 2 rows and 3 columns.
  6. Create an identity matrix of size 4x4.
  7. Create an array of numbers from 0 to 20 with a step of 5.
  8. Use slicing to extract elements 2 to 4 from this array: np.array([5, 10, 15, 20, 25, 30])
  9. Access the value 8 from this 2D array: np.array([[4, 8], [16, 32]])
  10. Generate 10 evenly spaced values between 0 and 100 using np.linspace().

💡 Need help? See the complete solution file on GitHub.

Tip: Try running these codes in your Python editor or Google Colab.

Post a Comment

Previous Post Next Post

POST ADS1