-
Notifications
You must be signed in to change notification settings - Fork 4.3k
[Edit] Python: NumPy: .transpose() #7045
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani 9f5c19b
Update datediff.md
mamtawardhani c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani 4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani 8325585
Merge branch 'Codecademy:main' into main
mamtawardhani 8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani 7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani 27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani 0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani 793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani 2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani 25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani 73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani 44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani 545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani 889b696
[Edit] Python: NumPy: .transpose()
mamtawardhani 2806e85
Update content/numpy/concepts/ndarray/terms/transpose/transpose.md
avdhoottt 1c4428e
Update content/numpy/concepts/ndarray/terms/transpose/transpose.md
avdhoottt 7ee20d6
Merge branch 'main' into numpy-transpose
avdhoottt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
150 changes: 130 additions & 20 deletions
150
content/numpy/concepts/ndarray/terms/transpose/transpose.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,67 +1,177 @@ | ||
| --- | ||
| Title: '.transpose()' | ||
| Description: 'Reverses or permutes the axes of an ndarray.' | ||
| Description: 'Returns a view of the array with axes permuted.' | ||
| Subjects: | ||
| - 'Computer Science' | ||
| - 'Data Science' | ||
| - 'Web Development' | ||
| Tags: | ||
| - 'Data Structures' | ||
| - 'Arrays' | ||
| - 'Functions' | ||
| - 'Data Structures' | ||
| - 'Methods' | ||
| - 'NumPy' | ||
| CatalogContent: | ||
| - 'learn-python-3' | ||
| - 'paths/data-science' | ||
| --- | ||
|
|
||
| The **`.transpose()`** method reverses or permutes the axes of an [`ndarray`](https://www.codecademy.com/resources/docs/numpy/ndarray). | ||
| The **`.transpose()`** method returns a view of the array with axes permuted. It rearranges the dimensions of a NumPy array by swapping or reordering its axes, effectively changing how data is organized without modifying the underlying data values. For a 2-D array, this performs the standard matrix transpose operation by swapping rows and columns. | ||
|
|
||
| The `.transpose()` method is essential for data manipulation tasks in scientific computing, machine learning, and data analysis. Common use cases include preparing data for matrix operations, reshaping arrays for different algorithms, converting between row-major and column-major formats, adapting image data for different processing libraries, and optimizing memory access patterns for performance-critical computations. | ||
|
|
||
| ## Syntax | ||
|
|
||
| ```pseudo | ||
| numpy.transpose(axes) | ||
| ndarray.transpose(*axes) | ||
| ``` | ||
|
|
||
| Where `axes` is a [`tuple`](https://www.codecademy.com/resources/docs/python/tuples) or list with as many entries as there are dimensions, listing the 0-based indices of each index in the new order in which they'll appear in the permuted array. If `axes` is omitted, `.transpose()` will reverse the order of axes. | ||
| **Parameters:** | ||
|
|
||
| Unlike the built-in [`numpy.transpose()`](https://www.codecademy.com/resources/docs/numpy/built-in-functions/transpose) function, the `numpy.ndarray.transpose()` method can accept the axes as separate arguments, as well as in the form of a tuple (i.e., `array.transpose(2,0,1)` is the same as `array.transpose((2,0,1))`). | ||
| - `*axes`: Variable length argument specifying the order of axes. Can be: | ||
| - No arguments: Reverses the order of all axes | ||
| - Tuple of integers: Specifies the permutation of axes (e.g., `(1, 0, 2)`) | ||
| - Separate integers: Individual axis indices as arguments (e.g., `1, 0, 2`) | ||
|
|
||
| If possible, the `ndarray` returned will be a view of the original `ndarray`'s data. | ||
| **Return value:** | ||
|
|
||
| ## Example | ||
| - `ndarray`: A view of the array with axes suitably permuted. | ||
|
|
||
| The example below creates a `ndarray` and then uses `.transpose()`. | ||
| ## Example 1: Basic Array Transposition | ||
|
|
||
| This example demonstrates the fundamental transpose operation on a 2-D array, showing how rows and columns are swapped: | ||
|
|
||
| ```py | ||
| import numpy as np | ||
|
|
||
| nd1 = np.array([[1,2,3],[4,5,6]]) | ||
| # Create a 2-D array | ||
| original_array = np.array([[1, 2, 3], | ||
| [4, 5, 6]]) | ||
|
|
||
| print("Original array:") | ||
| print(original_array) | ||
| print(f"Original shape: {original_array.shape}") | ||
|
|
||
| # Transpose the array | ||
| transposed_array = original_array.transpose() | ||
|
|
||
| print(nd1) | ||
| print(nd1.transpose()) | ||
| print("\nTransposed array:") | ||
| print(transposed_array) | ||
| print(f"Transposed shape: {transposed_array.shape}") | ||
| ``` | ||
|
|
||
| This produces the following output: | ||
| The output of this code will be: | ||
|
|
||
| ```shell | ||
| Original array: | ||
| [[1 2 3] | ||
| [4 5 6]] | ||
| Original shape: (2, 3) | ||
|
|
||
| Transposed array: | ||
| [[1 4] | ||
| [2 5] | ||
| [3 6]] | ||
| Transposed shape: (3, 2) | ||
| ``` | ||
|
|
||
| This example shows how the `.transpose()` method converts a 2×3 matrix into a 3×2 matrix by swapping rows and columns. The element at position `[0, 1]` (value 2) moves to position `[1, 0]` in the transposed array. | ||
|
|
||
| ## Example 2: Image Data Processing | ||
|
|
||
| This example demonstrates transposing image data arrays, a common operation in computer vision and image processing workflows: | ||
|
|
||
| ```py | ||
| import numpy as np | ||
|
|
||
| # Simulate RGB image data (Height, Width, Channels) | ||
| image_data = np.random.randint(0, 256, size=(100, 150, 3), dtype=np.uint8) | ||
|
|
||
| print("Original image shape (H, W, C):") | ||
| print(f"Height: {image_data.shape[0]}, Width: {image_data.shape[1]}, Channels: {image_data.shape[2]}") | ||
|
|
||
| # Transpose to (Width, Height, Channels) for certain processing libraries | ||
| transposed_image = image_data.transpose(1, 0, 2) | ||
|
|
||
| print("\nTransposed image shape (W, H, C):") | ||
| print(f"Width: {transposed_image.shape[0]}, Height: {transposed_image.shape[1]}, Channels: {transposed_image.shape[2]}") | ||
|
|
||
| # Alternative: Transpose to (Channels, Height, Width) for deep learning frameworks | ||
| channels_first = image_data.transpose(2, 0, 1) | ||
|
|
||
| print("\nChannels-first format (C, H, W):") | ||
| print(f"Channels: {channels_first.shape[0]}, Height: {channels_first.shape[1]}, Width: {channels_first.shape[2]}") | ||
| ``` | ||
|
|
||
| The output of this code will be: | ||
|
|
||
| ```shell | ||
| Original image shape (H, W, C): | ||
| Height: 100, Width: 150, Channels: 3 | ||
|
|
||
| Transposed image shape (W, H, C): | ||
| Width: 150, Height: 100, Channels: 3 | ||
|
|
||
| Channels-first format (C, H, W): | ||
| Channels: 3, Height: 100, Width: 150 | ||
| ``` | ||
|
|
||
| In the above output, the original array is a 2x3 matrix, and the transposed array is a 3x2 matrix. | ||
| This example shows how `.transpose()` is used to rearrange image data dimensions. Different image processing libraries and deep learning frameworks expect different axis orders, making transpose operations crucial for data compatibility. | ||
|
|
||
| ## Codebyte example | ||
| ## Codebyte Example: Matrix Operations for Machine Learning | ||
|
|
||
| This codebyte example demonstrates how to create and manipulate a multi-dimensional array in Python using NumPy’s `.transpose()` function. | ||
| This example illustrates using transpose for matrix multiplication operations commonly found in machine learning algorithms: | ||
avdhoottt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```codebyte/python | ||
| import numpy as np | ||
| a = np.ones((2, 3, 4, 5)) | ||
| print(np.transpose(a).shape) | ||
| # Create feature matrix (samples x features) | ||
| X = np.array([[1, 2, 3], | ||
| [4, 5, 6], | ||
| [7, 8, 9], | ||
| [10, 11, 12]]) | ||
| print("Feature matrix X (samples x features):") | ||
| print(X) | ||
| print(f"Shape: {X.shape}") | ||
| # Transpose for computing covariance matrix X^T * X | ||
| X_transposed = X.transpose() | ||
| print("\nTransposed matrix X^T (features x samples):") | ||
| print(X_transposed) | ||
| print(f"Shape: {X_transposed.shape}") | ||
| # Compute covariance matrix | ||
| covariance_matrix = np.dot(X_transposed, X) | ||
| print("\nCovariance matrix (X^T * X):") | ||
| print(covariance_matrix) | ||
| print(f"Shape: {covariance_matrix.shape}") | ||
| # Demonstrate matrix multiplication compatibility | ||
| weights = np.array([[0.5], [1.0], [1.5]]) # Feature weights | ||
| print(f"\nWeights shape: {weights.shape}") | ||
| # Matrix multiplication: X * weights | ||
| result = np.dot(X, weights) | ||
| print(f"Result shape after X * weights: {result.shape}") | ||
| ``` | ||
|
|
||
| This example demonstrates how transpose operations are fundamental in machine learning for computing covariance matrices, ensuring proper matrix multiplication dimensions, and preparing data for various algorithms that require specific matrix orientations. | ||
|
|
||
| ## Frequently Asked Questions | ||
|
|
||
| ### 1. Does `.transpose()` create a copy of the array? | ||
|
|
||
| No, `.transpose()` returns a view of the original array with rearranged axes. Changes to the transposed array will affect the original array. Use `.copy()` if you need an independent copy. | ||
|
|
||
| ### 2. What happens when transposing a 1-D array? | ||
|
|
||
| Transposing a 1-D array returns the same array unchanged, as a 1-D array has no rows or columns to swap. To convert a 1-D array to a column vector, use `arr[:, np.newaxis]` or `np.atleast_2d(arr).T`. | ||
|
|
||
| ### 3. What's the difference between `.transpose()` and `.T`? | ||
|
|
||
| `.T` is a shorthand property that only reverses all axes (equivalent to `.transpose()` with no arguments). `.transpose()` method allows custom axis specifications and is more flexible for multidimensional arrays. | ||
|
|
||
| ### 4. Is permute the same as transpose? | ||
|
|
||
| Yes, permute and transpose refer to the same operation in NumPy. Both terms describe rearranging the axes of an array. The `.transpose()` method permutes (rearranges) the axes according to the specified order, which is why the official documentation states it "permutes the dimensions of an array." | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.