Here's a cleaned-up version of your text without redundancy:
NumPy in Python
NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides
support for multi-dimensional arrays, mathematical functions, linear algebra, random number
generation, and more.
1. Installing NumPy
If you don’t have NumPy installed, you can install it using pip:
pip install numpy
2. Importing NumPy
import numpy as np
The alias np is commonly used for NumPy.
3. Creating NumPy Arrays
(a) 1D Array
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
(b) 2D Array (Matrix)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)
(c) Arrays with Zeros, Ones, or Empty Values
zeros = np.zeros((3, 3))
ones = np.ones((2, 2))
empty = np.empty((2, 2))
(d) Arrays with a Range of Numbers
arr_range = np.arange(1, 10, 2) # [1 3 5 7 9]
arr_linspace = np.linspace(0, 10, 5) # 5 evenly spaced numbers
4. Basic Array Operations
(a) Mathematical Operations
arr = np.array([1, 2, 3, 4])
print(arr + 2) # [3 4 5 6]
print(arr * 2) # [2 4 6 8]
print(arr ** 2) # [1 4 9 16]
(b) Element-wise Operations
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2) # [5 7 9]
print(arr1 * arr2) # [4 10 18]
5. Array Properties
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3) -> Rows, Columns
print(arr.size) # Total elements
print(arr.dtype) # Data type of elements
print(arr.ndim) # Number of dimensions
6. Reshaping and Transposing Arrays
(a) Reshaping
reshaped = arr.reshape(2, 3)
print(reshaped)
(b) Transposing
print(reshaped.T) # Swap rows and columns
7. Indexing and Slicing
(a) Indexing
print(arr[1, 2]) # Access specific element
(b) Slicing
print(arr[:, 1]) # Second column
print(arr[0, :]) # First row
8. Useful NumPy Functions
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr)) # Mean
print(np.sum(arr)) # Sum
print(np.min(arr)) # Min value
print(np.max(arr)) # Max value
print(np.std(arr)) # Standard deviation
print(np.var(arr)) # Variance
(b) Generating Random Numbers
rand_arr = np.random.rand(3, 3) # Random numbers (0 to 1)
rand_ints = np.random.randint(1, 10, (2, 2)) # Random integers
9. Linear Algebra in NumPy
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Matrix multiplication
result = np.dot(A, B)
print(result)
# Inverse and determinant
print(np.linalg.inv(A))
print(np.linalg.det(A))
10. Sorting and Searching
np.sort(arr) # Sorts array
np.argsort(arr) # Indices of sorted array
np.argmax(arr) # Index of max value
np.argmin(arr) # Index of min value
11. Saving and Loading NumPy Arrays
np.save("my_array.npy", arr) # Save
loaded_arr = np.load("my_array.npy") # Load
np.savetxt("data.csv", arr, delimiter=",") # Save as CSV
np.loadtxt("data.csv", delimiter=",") # Load CSV
Conclusion
NumPy provides efficient numerical operations and is essential for data science, machine
learning, and scientific computing.
This version removes redundant sections while keeping all key concepts. Let me know if you
need further refinements!