Introduction to NumPy Arrays in Python


What is NumPy?

NumPy (Numerical Python) is a powerful open-source library for numerical and scientific computing. It's widely used in data science, machine learning, and engineering applications.


Key Features:

  • Efficient multidimensional arrays (ndarray)
  • Mathematical and logical operations on arrays
  • Broadcasting functions
  • Linear algebra, Fourier transform, and random number capabilities

Installing NumPy

pip install numpy


Creating NumPy Arrays

import numpy as np

# 1D Array
arr1 = np.array([1, 2, 3, 4])
print("1D Array:", arr1)

# 2D Array
arr2 = np.array([[1, 2], [3, 4]])
print("2D Array:\n", arr2)

Output:

1D Array: [1 2 3 4]
2D Array:
 [[1 2]
 [3 4]]


NumPy Array Attributes

print("Shape:", arr2.shape)        # (2, 2)
print("Size:", arr2.size)          # 4
print("Data Type:", arr2.dtype)    # int64 or int32


Array Initialization Techniques

np.zeros((2, 3))         # 2x3 array of zeros
np.ones((3, 3))          # 3x3 array of ones
np.eye(3)                # Identity matrix
np.arange(0, 10, 2)      # [0 2 4 6 8]
np.linspace(0, 1, 5)     # 5 evenly spaced values between 0 and 1


Array Indexing and Slicing

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


Mathematical Operations on Arrays

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print("Addition:", a + b)        # [5 7 9]
print("Multiplication:", a * b)  # [4 10 18]
print("Mean:", np.mean(a))       # 2.0
print("Dot Product:", np.dot(a, b))  # 32


Reshaping Arrays

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

Output:

[[1 2 3]
 [4 5 6]]


Broadcasting in NumPy

a = np.array([[1, 2], [3, 4]])
b = np.array([10, 20])
print(a + b)

Output:

[[11 22]
 [13 24]]


Generating Random Arrays

np.random.rand(2, 3)     # Random float values
np.random.randint(0, 10, (2, 2))  # Random integers between 0-9