Part 2: Mastering NumPy Essentials
Welcome back to our "Unlocking the Power of NumPy" series! In this second installment, we'll dive deeper into the basics of NumPy, focusing on essential computations, universal functions, and array manipulation techniques. Whether you're new to NumPy or looking to reinforce your understanding of its core concepts, this article will provide valuable insights and practical examples to help you master the fundamentals of NumPy.
Create arrays from Python List:
import numpy as np
# Create a 1D array from a Python list
list_1d = [1, 2, 3, 4, 5]
array_1d = np.array(list_1d)
print("1D Array:")
print(array_1d)
# Create a 2D array from a nested Python list
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array_2d = np.array(list_2d)
print("\n2D Array:")
print(array_2d)
# Create a 3D array from a nested Python list
list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
array_3d = np.array(list_3d)
print("\n3D Array:")
print(array_3d)
This code snippet demonstrates how to create 1D, 2D, and 3D NumPy arrays from Python lists. You can use the np.array()
function with a Python list as the argument to convert the list into a NumPy array of the desired dimensions.
Creating arrays from scratch:
import numpy as np
# Create a 1D array filled with zeros
zeros_array = np.zeros(5)
print("Zeros Array (1D):\n", zeros_array)
# Output:
# Zeros Array (1D):
# [0. 0. 0. 0. 0.]
# Create a 2D array filled with ones
ones_array = np.ones((2, 3))
print("\nOnes Array (2D):\n", ones_array)
# Output:
# Ones Array (2D):
# [[1. 1. 1.]
# [1. 1. 1.]]
# Create a 3x3 array filled with a specific value
full_array = np.full((3, 3), 7)
print("\nFull Array (3x3):\n", full_array)
# Output:
# Full Array (3x3):
# [[7 7 7]
# [7 7 7]
# [7 7 7]]
# Create a 1D array with values from 0 to 9
arange_array = np.arange(10)
print("\nArange Array (1D):\n", arange_array)
# Output:
# Arange Array (1D):
# [0 1 2 3 4 5 6 7 8 9]
# Create a 1D array with 5 evenly spaced values between 0 and 10
linspace_array = np.linspace(0, 10, 5)
print("\nLinspace Array (1D):\n", linspace_array)
# Output:
# Linspace Array (1D):
# [ 0. 2.5 5. 7.5 10. ]
# Create a 2x2 array with random values between 0 and 1
random_array = np.random.random((2, 2))
print("\nRandom Array (2x2):\n", random_array)
# Create a 2x2 array with random values from a normal distribution
normal_array = np.random.normal(0, 1, (2, 2))
print("\nNormal Array (2x2):\n", normal_array)
# Create a 2x2 array with random integers between 0 and 10
randint_array = np.random.randint(0, 10, (2, 2))
print("\nRandint Array (2x2):\n", randint_array)
# Create a 3x3 identity matrix
eye_array = np.eye(3)
print("\nIdentity Array (3x3):\n", eye_array)
# Output:
# Identity Array (3x3):
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
These examples demonstrate the usage of NumPy functions np.zeros()
, np.ones()
, np.full()
, np.arange()
, np.linspace()
, np.random.random()
, np.random.normal()
, np.random.randint()
, np.eye()
, and np.empty()
to create arrays with specific properties such as shape, values, and distribution.
Attributes of numpy array:
The rank of an array is the number of dimensions it contains.The shape of an array is a tuple of integers giving the size of the array along each dimension.The size of an array is the number of elements it contains (which is equivalent to the product of the array’s dimensions).
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Get the rank (number of dimensions) of the array
rank = arr.ndim
# Get the shape of the array
shape = arr.shape
# Get the size (number of elements) of the array
size = arr.size
# Print the results
print("Rank of the array:", rank)
print("Shape of the array:", shape)
print("Size of the array:", size)
Output
Rank of the array: 2
Shape of the array: (2, 3)
Size of the array: 6
Indexing:
NumPy arrays can be indexed by integers, a tuple of nonnegative integers, by booleans or by another array.
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Accessing a single element
print("Element at index (0, 0):", arr[0, 0])
# Accessing a row
print("First row:", arr[0])
# Accessing a column
print("Second column:", arr[:, 1])
Element at index (0, 0): 1
First row: [1 2 3]
Second column: [2 5 8]
Array Slicing:
It allows you to extract a subset of elements from a NumPy array. It's similar to list slicing in Python but with additional capabilities for multi-dimensional arrays. You can use slicing notation with square brackets []
to specify the start, stop, and step for each dimension of the array. Here's how you can do it:
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Basic slicing
slice_1 = arr[0:2, 1:3] # Extracts a subarray from rows 0 to 1 and columns 1 to 2
print("Basic slicing:")
print(slice_1)
# Slicing with step
slice_2 = arr[::2, ::2] # Extracts every other row and column
print("\nSlicing with step:")
print(slice_2)
# Slicing with negative indices
slice_3 = arr[-1:, :] # Extracts the last row
print("\nSlicing with negative indices:")
print(slice_3)
# Assigning a new value to a slice
arr[1:3, 1:3] = 0 # Assigns 0 to the subarray from rows 1 to 2 and columns 1 to 2
print("\nArray after assigning a new value to a slice:")
print(arr)
#output
Basic slicing:
[[2 3]
[6 7]]
Slicing with step:
[[1 3]
[9 11]]
Slicing with negative indices:
[[ 9 10 11 12]]
Array after assigning a new value to a slice:
[[ 1 2 3 4]
[ 5 0 0 8]
[ 9 0 0 12]]
Reshaping of Arrays:
Reshaping arrays in NumPy allows you to change the shape (dimensions) of the array without changing the data it contains. This can be useful for tasks such as converting a 1D array into a 2D array or vice versa, or for preparing data for certain operations or models. You can use the reshape()
function to reshape arrays in NumPy. Here's how you can do it:
import numpy as np
# Create a 1D array
arr_1d = np.array([1, 2, 3, 4, 5, 6])
# Reshape the 1D array to a 2D array with 2 rows and 3 columns
arr_2d = arr_1d.reshape(2, 3)
print("Original 1D array:")
print(arr_1d)
print("\nReshaped 2D array:")
print(arr_2d)
# Create a 2D array
arr_2d = np.array([[1, 2, 3],
[4, 5, 6]])
# Reshape the 2D array to a 1D array
arr_1d = arr_2d.reshape(-1) # Use -1 to infer the size of the remaining dimensions
# Alternatively, you can specify the size directly: arr_1d = arr_2d.reshape(6)
print("\nOriginal 2D array:")
print(arr_2d)
print("\nReshaped 1D array:")
print(arr_1d)
#Output:
Original 1D array:
[1 2 3 4 5 6]
Reshaped 2D array:
[[1 2 3]
[4 5 6]]
Original 2D array:
[[1 2 3]
[4 5 6]]
Reshaped 1D array:
[1 2 3 4 5 6]Original 1D array:
[1 2 3 4 5 6]
Reshaped 2D array:
[[1 2 3]
[4 5 6]]
Original 2D array:
[[1 2 3]
[4 5 6]]
Reshaped 1D array:
[1 2 3 4 5 6]
Concatenating and splitting of arrays:
Concatenating arrays in NumPy allows you to combine multiple arrays into a single array along a specified axis. NumPy provides the np.concatenate()
function for this purpose. Similarly, splitting arrays allows you to divide an array into multiple smaller arrays along a specified axis. You can use functions like np.split()
, np.hsplit()
, or np.vsplit()
for splitting arrays. Here's how you can perform concatenation and splitting:
import numpy as np
# Create two arrays
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
# np.hstack() example
hstack_result = np.hstack((arr1, arr2))
print("Horizontally stacked array:\n", hstack_result)
# np.vstack() example
vstack_result = np.vstack((arr1, arr2))
print("\nVertically stacked array:\n", vstack_result)
# np.concatenate() example along axis 0 (vertical concatenation)
concatenated_vertically = np.concatenate((arr1, arr2), axis=0)
print("\nConcatenated vertically using np.concatenate:\n", concatenated_vertically)
# np.concatenate() example along axis 1 (horizontal concatenation)
concatenated_horizontally = np.concatenate((arr1, arr2), axis=1)
print("\nConcatenated horizontally using np.concatenate:\n", concatenated_horizontally)
# np.split() example - splitting along axis 0
split_vertically = np.split(concatenated_vertically, 2, axis=0)
print("\nSplit vertically using np.split:")
for a in split_vertically:
print(a)
# np.split() example - splitting along axis 1
split_horizontally = np.split(concatenated_horizontally, 2, axis=1)
print("\nSplit horizontally using np.split:")
for a in split_horizontally:
print(a)
#output
Horizontally stacked array:
[[1 2 5 6]
[3 4 7 8]]
Vertically stacked array:
[[1 2]
[3 4]
[5 6]
[7 8]]
Concatenated vertically using np.concatenate:
[[1 2]
[3 4]
[5 6]
[7 8]]
Concatenated horizontally using np.concatenate:
[[1 2 5 6]
[3 4 7 8]]
Split vertically using np.split:
[[1 2]
[3 4]]
[[5 6]
[7 8]]
Split horizontally using np.split:
[[1 2]
[3 4]]
[[5 6]
[7 8]]
Conclusion:Mastering the essentials of NumPy lays a solid foundation for advanced data manipulation and analysis tasks in Python. In this article, we've explored key concepts including arrays, indexing, slicing, reshaping, concatenation and splitting.By understanding these fundamentals, you'll be well-equipped to tackle more complex data science challenges with NumPy. Stay tuned for our next article, where we'll delve into advanced techniques and functionalities of NumPy.