0% found this document useful (0 votes)
2 views

M3__NumPy Essentials-The NumPy Array

The document provides an introduction to NumPy, a popular open-source library in Python for numerical computing, highlighting its efficiency in handling arrays and performing mathematical operations. It covers key features such as array creation, attributes, indexing, slicing, and operations including statistical functions and broadcasting. Additionally, it includes example programs demonstrating array manipulation, searching, sorting, and plotting using NumPy.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

M3__NumPy Essentials-The NumPy Array

The document provides an introduction to NumPy, a popular open-source library in Python for numerical computing, highlighting its efficiency in handling arrays and performing mathematical operations. It covers key features such as array creation, attributes, indexing, slicing, and operations including statistical functions and broadcasting. Additionally, it includes example programs demonstrating array manipulation, searching, sorting, and plotting using NumPy.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

www.acharya.ac.

in

Dept. of MCA
Dept. of MCA

Shaheena KV,Dept.of MCA


Introduction to NumPy

• NumPy stands for "Numerical Python."

• NumPy is a popular library in Python for numerical computing.

• It is an open-source Python library used for numerical and scientific


computing.

Dept. of MCA • Provides support for arrays, matrices, and a variety of mathematical
functions.

• Essential for data analysis, machine learning, and scientific


computing.
Why Use NumPy?
• Faster and more efficient than Python lists.

• Ideal for handling large datasets and performing numerical


computations.

• Widely used in data science, machine learning, and scientific


applications.
Dept. of MCA
What is a NumPy Array?
• Definition: A NumPy array is a grid of values, all of the same type,
and is indexed by a tuple of nonnegative integers.

• Homogeneous: All elements must have the same data type.

• Efficient: Uses less memory and allows faster computation


Dept. of MCA compared to Python lists.

• Supports Multi-dimensional Arrays: Can represent scalars (0D),


vectors (1D), matrices (2D), and higher dimensions (nD).

• The NumPy library has a large set of routines (built-in functions)


for creating, manipulating, and transforming NumPy arrays.
Creating a NumPy Array
• Importing NumPy: import numpy as np

• Methods to Create Arrays:


import numpy as np
# Creating a 1D array
arr = np.array([1, 2, 3, 4])
Dept. of MCA
# Creating a 2D array
arr_2d = np.array([[1, 2], [3, 4]])

# Creating arrays with default values


zeros = np.zeros((2, 3)) # 2x3 array of zeros
ones = np.ones((3, 3)) # 3x3 array of ones
identity = np.eye(4) # 4x4 identity matrix
NumPy Array Attributes
Attribute Description
.shape Returns dimensions of the array
.size Total number of elements in the array
.dtype Data type of array elements
.ndim Number of dimensions

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


Dept. of MCA

print("Shape:", array.shape) # (2, 3) -> rows and columns


print("Size:", array.size) # Total number of elements
print("Data Type:", array.dtype) # Data type of elements
print("Dimensions:", array.ndim) # Number of dimensions
Array Indexing and Slicing
array = np.array([10, 20, 30, 40, 50])

# Indexing

print(array[0]) # Access the first element -> 10

print(array[-1]) # Access the last element -> 50


Dept. of MCA
# Slicing

print(array[1:4]) # [20, 30, 40]

print(array[:3]) # [10, 20, 30]

print(array[::2]) # [10, 30, 50]


Operations on NumPy Arrays
• Mathematical Operations

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

# Element-wise addition
print(a + b) # [5, 7, 9]
Dept. of MCA

# Element-wise multiplication
print(a * b) # [4, 10, 18]

# Scalar operations
print(a * 2) # [2, 4, 6]
• Statistical Operations

array = np.array([10, 20, 30, 40])


print("Mean:", array.mean()) # Average value
print("Sum:", array.sum()) # Sum of all elements
print("Max:", array.max()) # Maximum value
print("Min:", array.min()) # Minimum value
Dept. of MCA
• Reshaping and Flattening Arrays
array = np.array([[1, 2], [3, 4], [5, 6]])

# Reshaping-Change the shape (dimensions) of an array


without changing its data.

reshaped_array = array.reshape(2, 3)
print("Reshaped Array:\n", reshaped_array)

Dept. of MCA
# Flattening-Convert a multi-dimensional array into a 1D
array.

flattened_array = array.flatten()
print("Flattened Array:", flattened_array)
• Special Arrays
• np.linspace(start, stop, num): Creates an array with evenly spaced
numbers.
linspace_array = np.linspace(0, 1, 5)
print("Linspace Array:", linspace_array) # [0., 2.5, 5., 7.5, 10.]

• np.arange(start, stop, step): Creates an array with numbers in a


range.

Dept. of MCA
arange_array = np.arange(0, 10, 2)
print("Arange Array:", arange_array) # [0, 2, 4, 6, 8]

• np.random.rand(shape): Generates random values.


# Random
random_array = np.random.rand(3, 3)
print("Random Array:\n", random_array)
• Broadcasting in NumPy- Broadcasting allows operations
on arrays of different shapes.

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


scalar = 5
print(array + scalar) # [6, 7, 8]
Dept. of MCA
Program 1: Array Manipulation, Searching,
Sorting, and Splitting
import numpy as np
# Part 1: Array Manipulation
print("Array Manipulation:")
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original Array:\n", arr)
Dept. of MCA # Reshaping the array
reshaped = arr.reshape(1, 9)
print("Reshaped Array (1x9):\n", reshaped)
# Flattening the array
flattened = arr.flatten()
print("Flattened Array:\n", flattened)
# Part 2: Searching
print("\nSearching:")
search_value = 5
index = np.where(arr == search_value)
print(f"Index of {search_value}: {index}")

# Part 3: Sorting
print("\nSorting:")
unsorted = np.array([8, 3, 1, 7, 2])
Dept. of MCA
sorted_array = np.sort(unsorted)
print("Unsorted Array:", unsorted)
print("Sorted Array:", sorted_array)

# Part 4: Splitting
print("\nSplitting:")
split_array = np.split(flattened, 3) # Splitting into 3 equal parts
print("Split Arrays:", split_array)
Program 2: Broadcasting and Plotting NumPy
Arrays
a) Broadcasting Example
import numpy as np
print("Broadcasting Example:")
# Create a 1D array and a 2D array
arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20], [30]])
Dept. of MCA
# Broadcasting: Adding 1D array to 2D array
result = arr1 + arr2
print("1D Array:\n", arr1)
print("2D Array:\n", arr2)
print("Broadcasted Result (Addition):\n", result)
b) Plotting NumPy Arrays
import numpy as np
import matplotlib.pyplot as plt
# Generate x and y values
x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x) # Compute sine values for each x
# Plotting
Dept. of MCA plt.plot(x, y, label="sin(x)", color="blue")
plt.title("Plotting NumPy Array")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid()
plt.show()
Shaheena KV
Dept.of MCA

Dept. of MCA

You might also like