Python - NumPy Part 4: Reshaping and Manipulating Arrays
Reshaping allows flexibility in structuring data, while manipulation enables dynamic modifications.
Examples and Explanation
Reshaping Arrays
array = np.arange(1, 10)
reshaped = array.reshape(3, 3)
print(reshaped)
# Output:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
Explanation: Reshape the array to any compatible dimensions. This is crucial for handling multidimensional data.
Flattening Arrays
flat = reshaped.flatten()
print(flat) # Output: [1 2 3 4 5 6 7 8 9]
Explanation: Converts multi-dimensional arrays back to 1D.
Concatenating Arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
print(np.concatenate((array1, array2))) # Output: [1 2 3 4 5 6]
Explanation: Joins two or more arrays along an existing axis.
Splitting Arrays
split = np.split(array, 3)
print(split) # Output: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
Explanation: Divides arrays into smaller sub-arrays.
Transposing Arrays
print(reshaped.T)
# Output:
# [[1 4 7]
# [2 5 8]
# [3 6 9]]
Explanation: Switches rows and columns, commonly used in matrix computations.