M3__NumPy Essentials-The NumPy Array
M3__NumPy Essentials-The NumPy Array
in
Dept. of MCA
Dept. of MCA
Dept. of MCA • Provides support for arrays, matrices, and a variety of mathematical
functions.
# Indexing
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
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.]
Dept. of MCA
arange_array = np.arange(0, 10, 2)
print("Arange Array:", arange_array) # [0, 2, 4, 6, 8]
# 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