Numpy 2D Array
Numpy is a fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. This article focuses on 2D arrays in Numpy, exploring their creation, manipulation, and application through various examples.
1. Introduction to Numpy 2D Arrays
A 2D array in Numpy is a grid of values, all of the same type, indexed by a tuple of non-negative integers. The dimensions are called axes; the number of axes is the rank. In the case of a 2D array, the array has a rank of 2 (i.e., two dimensions). Each element in a 2D array can be accessed using a pair of indices representing the row and column.
Example 1: Creating a 2D Array
import numpy as np
# Create a 2D array from a list of lists
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array_2d)
Output:
2. Accessing Elements in a 2D Array
Elements in a 2D array can be accessed directly by specifying row and column indices in square brackets.
Example 2: Accessing an Element
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
element = array_2d[1, 2] # Access the element at row 1, column 2
print(element)
Output:
3. Slicing 2D Arrays
Slicing in Python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end]
. We can also define the step, like this: [start:end:step]
.
Example 3: Slicing a Row
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row_slice = array_2d[1, :] # Slice the second row
print(row_slice)
Output:
Example 4: Slicing a Column
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
column_slice = array_2d[:, 2] # Slice the third column
print(column_slice)
Output:
4. Modifying 2D Arrays
You can modify an existing array by assigning a new value to a specific element or slice.
Example 5: Modifying an Element
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
array_2d[0, 0] = 10 # Change the element at row 0, column 0
print(array_2d)
Output:
Example 6: Modifying a Slice
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
array_2d[2, :] = [10, 11, 12] # Change the entire third row
print(array_2d)
Output:
5. Operations on 2D Arrays
Numpy provides a wide range of mathematical operations that can be performed on arrays. These include operations between arrays (element-wise), operations along an axis, and matrix operations.
Example 7: Element-wise Addition
import numpy as np
array_1 = np.array([[1, 2, 3], [4, 5, 6]])
array_2 = np.array([[7, 8, 9], [10, 11, 12]])
result = np.add(array_1, array_2)
print(result)
Output:
Example 8: Matrix Multiplication
import numpy as np
array_1 = np.array([[1, 2], [3, 4]])
array_2 = np.array([[5, 6], [7, 8]])
result = np.dot(array_1, array_2)
print(result)
Output:
6. Reshaping 2D Arrays
Reshaping provides a way to change the structure of an array without changing its data.
Example 9: Reshape an Array
import numpy as np
array_1d = np.array([1, 2, 3, 4, 5, 6])
array_2d = np.reshape(array_1d, (2, 3)) # Reshape to 2 rows and 3 columns
print(array_2d)
Output:
7. Transposing 2D Arrays
Transposing is a special form of reshaping which completely flips the axes.
Example 10: Transpose an Array
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
transposed = np.transpose(array_2d)
print(transposed)
Output:
8. Stacking and Splitting Arrays
Stacking is the process of joining a sequence of arrays along a new axis. Splitting is the opposite, breaking one array into multiple.
Example 11: Vertical Stacking
import numpy as np
array_1 = np.array([[1, 2], [3, 4]])
array_2 = np.array([[5, 6], [7, 8]])
stacked = np.vstack((array_1, array_2))
print(stacked)
Output:
Example 12: Horizontal Splitting
import numpy as np
array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
split = np.hsplit(array, 2) # Split into 2 equal parts
print(split[0])
print(split[1])
Output:
9. Broadcasting in 2D Arrays
Broadcasting describes how numpy treats arrays with different shapes during arithmetic operations.
Example 13: Broadcasting Addition
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10
result = array_2d + scalar # Add scalar to each element
print(result)
Output:
10. Mathematical Functions
Numpy provides a comprehensive set of mathematical functions that can be applied element-wise to arrays.
Example 14: Computing the Sine
import numpy as np
angles = np.array([[0, 30, 45], [60, 90, 120]])
radians = np.deg2rad(angles)
sine_values = np.sin(radians)
print(sine_values)
Output:
11. Statistical Methods
Numpy offers common statistical methods that can be applied to arrays, such as mean, median, and standard deviation.
Example 15: Calculating the Mean
import numpy as np
array = np.array([[1, 2, 3], [4, 5, 6]])
mean_value = np.mean(array)
print(mean_value)
Output:
12. Linear Algebra in Numpy
Numpy is equipped with a module for linear algebra, numpy.linalg
, which provides a host of methods for performing matrix operations.
Example 16: Finding the Determinant
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
determinant = np.linalg.det(matrix)
print(determinant)
Output:
13. Loading and Saving Arrays
Numpy provides easy-to-use functions to save and load arrays to and from disk.
Example 17: Saving an Array
import numpy as np
array = np.array([[1, 2, 3], [4, 5, 6]])
np.save('numpyarray_com_array.npy', array)
Example 18: Loading an Array
import numpy as np
array = np.load('numpyarray_com_array.npy')
print(array)
Output:
14. Random Number Generation
Numpy has a built-in module for generating random numbers, which can be used to create random arrays.
Example 19: Creating a Random Array
import numpy as np
random_array = np.random.rand(2, 3) # 2 rows, 3 columns
print(random_array)
Output:
Example 20: Full Example
import numpy as np
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Access an element
element = array_2d[1, 2]
print('Element:', element)
# Slice a row
row_slice = array_2d[1, :]
print('Row slice:', row_slice)
# Modify an element
array_2d[0, 0] = 10
print('Modified array:', array_2d)
# Perform an operation
result = array_2d + 10
print('Result:', result)
# Reshape the array
reshaped = np.reshape(array_2d, (1, 9))
print('Reshaped:', reshaped)
# Transpose the array
transposed = np.transpose(array_2d)
print('Transposed:', transposed)
# Save the array
np.save('numpyarray_com_array.npy', array_2d)
# Load the array
loaded = np.load('numpyarray_com_array.npy')
print('Loaded:', loaded)
Output:
This concludes our comprehensive guide to Numpy 2D arrays. Happy coding with Numpy at numpyarray.com!