import numpy as np
# Example for `reshape`
b = np.array([1, 2, 3])
reshaped_b = b.reshape(3, 1)
print(reshaped_b)
**Output**:
[[1]
[2]
[3]]
**Explanation**:
- The original array `b` is a 1D array with shape `(3,)`.
- `reshape(3, 1)` converts it into a 2D array with shape `(3, 1)`, resulting in three rows and one column.
**Key Point**: `reshape` is used to change the dimensions of an array while preserving its data, as long as the new shape has the same number of elements as the original shape.
# Example for `transpose`
b = np.array([[1, 2, 3], [4, 5, 6]])
transposed_b = b.T
print(transposed_b)
**Output**:
[[1 4]
[2 5]
[3 6]]
**Explanation**:
- The original array `b` is a 2D array with shape `(2, 3)` (2 rows and 3 columns).
- The `transpose()` method (or `b.T`) switches rows and columns, converting it to a shape of `(3, 2)`.
**Key Point**: `transpose` is used to swap the dimensions of an array. For 2D arrays, it effectively flips the array over its diagonal.
# Example for `axis` with operations like sum
b = np.array([[1, 2, 3], [4, 5, 6]])
sum_along_axis0 = np.sum(b, axis=0)
sum_along_axis1 = np.sum(b, axis=1)
print("Sum along axis 0:", sum_along_axis0)
print("Sum along axis 1:", sum_along_axis1)
**Output**:
Sum along axis 0: [5 7 9]
Sum along axis 1: [ 6 15]
**Explanation**:
- `axis=0` refers to the vertical axis (columns), so summing along `axis=0` sums each column.
- `axis=1` refers to the horizontal axis (rows), so summing along `axis=1` sums each row.
**Key Point**: The concept of `axis` is not about reshaping or transposing but about how operations are performed across dimensions of the array.
### Summary:
- **`reshape`**: Changes the shape of an array while keeping the same data. Useful for reformatting arrays without altering their content.
- **`transpose`**: Swaps the dimensions of the array. For 2D arrays, it converts rows to columns and vice versa.
- **`axis`**: Defines the direction along which operations (like sum, mean) are applied. It’s crucial for performing operations that aggregate or reduce data along specific dimensions.
### Visualizing the Difference:
For a 2D array like `[[1, 2, 3], [4, 5, 6]]`:
- **`reshape(3, 2)`**: Converts it to `[[1, 2], [3, 4], [5, 6]]`, rearranging the elements into a new shape.
- **`transpose()`**: Converts it to `[[1, 4], [2, 5], [3, 6]]`, switching rows with columns.
Each of these operations is useful in different contexts, depending on what you need to achieve with the array's structure.
No comments:
Post a Comment