python numpy reshape example
numpy.reshape() is used to change the shape of the array without changing the data. 1. The basic operation is to convert a one-dimensional array of 6 elements into a (2,3) two-dimensional array; 2. Use -1 to automatically infer dimensions, such as reshape(2,-1) or reshape(-1,4); 3. Multi-dimensional conversion can be performed, such as converting a one-dimensional array of 24 elements into a three-dimensional array of (2,3,4); 4. Use reshape(-1) to efficiently flatten the array into one-dimensional; 5. Reshape does not modify the original array, return the new array, and the original array remains unchanged; note that the total number of new and old shape elements must be consistent, otherwise an error will be reported.
numpy.reshape()
is a very common method in NumPy, which is used to change the shape of an array without changing its data. The following is a few common examples to intuitively understand its usage.

1. Basic reshape operation
Convert a one-dimensional array to a two-dimensional array (for example 1x6 → 2x3):
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) reshapeed = arr.reshape(2, 3) print(reshaped)
Output:

[[1 2 3] [4 5 6]]
Note: The number of original elements is 6, and the shape (2,3) after reshape must also be 6 elements, otherwise an error will be reported.
2. Use -1 to automatically infer dimensions
You can use -1
to make NumPy automatically calculate the size of a certain dimension:

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Convert to 2 rows, automatically infer the number of columns reshaped = arr.reshape(2, -1) print(reshaped)
Output:
[[1 2 3 4] [5 6 7 8]]
It can also be written as (-1, 4)
, indicating that the number of rows is automatically calculated, with 4 columns per row.
3. Multidimensional reshape (for example, 1D → 3D)
arr = np.arange(24) # [0, 1, ..., 23] reshapeed = arr.reshape(2, 3, 4) print(reshaped.shape) # (2, 3, 4) print(reshaped)
The output is a 3D array of 2 layers, 3 rows and 4 columns per layer.
4. reshape back to one-dimensional array
arr = np.array([[1, 2], [3, 4], [5, 6]]) # shape (3, 2) flat = arr.reshape(-1) # Flatten to one-dimensional print(flat) # [1 2 3 4 5 6]
This is equivalent to .flatten()
, but reshape(-1)
is more efficient and does not copy data (if possible).
5. Note: reshape does not change the original array
arr = np.array([1, 2, 3, 4]) new_arr = arr.reshape(2, 2) print(arr) # Still [1 2 3 4] print(new_arr) # [[1 2], [3 4]]
reshape
returns the new array, the original array remains unchanged (unless the view cannot be viewed, it will be copied).
Common error: element count mismatch
arr = np.array([1, 2, 3]) # arr.reshape(2, 2) # Error! 3 elements cannot be turned into 2x2 (4 are required)
An error will be reported:
ValueError: cannot reshape array of size 3 into shape (2,2)
Summary: Key points for using reshape
- The total number of elements in old and new shapes must be consistent.
- Use
-1
to automatically infer a certain dimension (but only one -1). - Commonly used for data preprocessing, such as image and machine learning input adjustment.
-
reshape(-1)
is an efficient way to flatten arrays.
Basically all that, not complicated but very practical.
The above is the detailed content of python numpy reshape example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

First,checkiftheFnkeysettingisinterferingbytryingboththevolumekeyaloneandFn volumekey,thentoggleFnLockwithFn Escifavailable.2.EnterBIOS/UEFIduringbootandenablefunctionkeysordisableHotkeyModetoensurevolumekeysarerecognized.3.Updateorreinstallaudiodriv

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

Computed has a cache, and multiple accesses are not recalculated when the dependency remains unchanged, while methods are executed every time they are called; 2.computed is suitable for calculations based on responsive data. Methods are suitable for scenarios where parameters are required or frequent calls but the result does not depend on responsive data; 3.computed supports getters and setters, which can realize two-way synchronization of data, but methods are not supported; 4. Summary: Use computed first to improve performance, and use methods when passing parameters, performing operations or avoiding cache, following the principle of "if you can use computed, you don't use methods".
