The N-dimensional array is going to be the primary data structure that you work with while using NumPy. One or more dimensions may be used to shape the data contained inside an array. It’s possible that some applications may need you to rearrange the way in which your data is stored inside a NumPy array. To reorganise the data, you may make use of NumPy’s reshape() function.
The number of dimensions included inside an array as well as the size of each dimension are both referred to as the array’s form. You are going to learn how to modify the form of a NumPy array so that its contents may be reorganised in a different fashion during the course of this lesson. After you’ve finished going through this course, you’ll be able to change the structure of any array to make it work better for the application you’re developing. You will learn how to do the following at the end of this guide:
Change the shape
of a NumPy array without changing its number of dimensions
Add and remove dimensions
in a NumPy array
Control how data is rearranged
when reshaping an array with the
Use a wildcard value
for one of the dimensions in
In order to follow along with this lesson, you need have some prior experience with NumPy and N-dimensional arrays. Before getting started with NumPy, you may learn more about it by reading the NumPy Tutorial, which is titled Your First Steps Into Data Science in Python.
To investigate the reshape() function and execute the code in this tutorial, you will need to have NumPy already installed in your environment. Inside a virtual environment, the package may be installed using the pip package installation tool. To see the instructions for your operating system, choose either the Windows or Linux + macOS option in the following table.
PS> python -m venv venv PS> .\venv\Scripts\activate (venv) PS> python -m pip install numpy
$ python -m venv venv $ source venv/bin/activate (venv) $ python -m pip install numpy
When importing NumPy, it is customary to refer to the library by its shorthand name, np. Importing NumPy in the Python REPL is the first step towards getting started.
>>> import numpy as np
After the successful installation of NumPy and the subsequent import of the package into a REPL environment, you are now prepared to begin using NumPy.
Understand the Shape of NumPy Arrays
During this course, you will work with NumPy’s ndarray. You are going to go over the most important aspects of this data structure in this part. These aspects include the general form of an array as well as the number of dimensions it has.
A list of items may be used to generate an array.
>>> import numpy as np >>> numbers = np.array([[1, 2, 3, 4], [5, 6 >>>
>>> numbers.ndim 2
The number array is of a two-dimensional format (2D). You are able to organise the same information that is included in integers in arrays that have a varied number of dimensions, including the following:
The array that has the form (8,) is a one-dimensional (1D) array, but the array that has the shape (2, 2, 2) is a three-dimensional (3D) array (3D). Both arrays have the identical information, which consists just of integers.
To comprehend the structure of the array, you may make use of the.shape property.
Number of dimensions:
The length of the tuple
shows you how many dimensions are in the array. For example,
contains two items, which means that an array with this shape is a 2D array.
Length of each dimension:
The integers in
represent the length of each dimension in the array. For example, if the shape of an array is
, then the first dimension has a length of 2 and the second dimension has a length of 4.
You may get an understanding of the structure of the arrays that you are dealing with by using the information that is provided in the tuple.shape file.
The reshape() function of NumPy enables you to alter the structure of an array without affecting the data contained inside it. An array may be reorganised into a new arrangement using the same number of dimensions or a different number of dimensions altogether.
In the sections that follow, you'll go through a few quick examples that demonstrate how to utilise the reshape() function to turn arrays from one shape into another.
Change an Array’s Shape Using NumPy
You are able to modify the shape of an array into another form that is compatible with it by using the reshape() function. Since each component from the old array has to be able to find a home in the new array, only some of the possible forms may be used.
You have the option of calling reshape() either as a method or a function. According to the documentation for the function, there are three possible
is the original array.
is a tuple or an integer with the shape of the new array. When
is an integer, the new array will have one dimension.
enables you to determine how the data is configured in the new array.
In this part, you will be responsible for using the first two parameters. In the next walkthrough, the topic of order will be covered.
You will no longer be required to utilise the first parameter, which is denoted by the letter a, when using the reshape() function of the np.ndarray class. This is because the object is always supplied to the method as the first argument. During the remainder of this course, you will be applying the reshape() function. On the other hand, what you find out about this approach applies as well to the function. Please take note that a method is a function that is defined inside the body of a class. You may invoke the reshape() method by using the notation np.reshape(a, newshape). a.reshape(newshape) is the equivalent of calling out the method.
You will investigate NumPy's reshape() function by working through an example in this part of the lesson. The head of computers at a school wants certain data to be transformed, and you will need to build some code to assist him.
There are a total of 50 students enrolled in the five courses that make up the same grade level. The answers of the test, after being anonymised, are stored for each student in a two-dimensional array. The array has the form of a (5, 10) rectangle. The five rows symbolise the classes, and within each row is the test score for every student who is enrolled in that particular class.
You are able to generate a new version of this array by populating its elements with random values. Using the default rng() generator and then using one of its methods will allow you to produce random values in NumPy. This may be done at any time. In this particular instance, you make a call to.integers ()
>>> import numpy as np >>> rng = np.random.default_rng() >>> results = rng.integers(0, 100, size=(5, 10)) >>> results array([[53, 28, 33, 23, 81, 58, 16, 6, 91, 84], [ 4, 20, 20, 27, 27, 82, 19, 76, 57, 47], [56, 97, 53, 21, 72, 18, 91, 29, 38, 15], [85, 20, 30, 67, 65, 1, 52, 95, 87, 70], [66, 70, 9, 30, 73, 1, 56, 29, 10, 76]])
Using the range specified by the first two parameters, the.numbers() function generates random integers with a uniform distribution that fall inside that range. The size of the array is determined by the third input, which is called size. While it is more simple to use the uniform distribution of integers for this example, you are free to use any other distribution you choose.
The head of computing performed an individual analysis on the results of each class and has decided that in order to continue working on the year as a whole, the array should be converted into a single row that contains all of the results.
Converting the array that now has five rows and ten columns into a new array that has one row and fifty columns is one of the available options. You may do this by using the reshape function ()
>>> year_results array([53, 28, 33, 23, 81, 58, 16, 6, 91, 84, 4, 20, 20, 27, 27, 82, 19, 76, 57, 47, 56, 97, 53, 21, 72, 18, 91, 29, 38, 15, 85, 20, 30, 67, 65, 1, 52, 95, 87, 70, 66, 70, 9, 30, 73, 1, 56, 29, 10, 76]) >>> year_results[0, 0] 53
The row is referred to by the index 0 whenever a single index is used, such as in the expression year results. You may access the first element by entering year results[0, 0] into the access field.
Reduce an Array’s Number of Dimensions
It is not necessary for the newly created array to have the same number of dimensions as the one it is replacing when you use the reshape() function. You have the ability to reformat the initial results array from previously into a 1D format.
>>> year_results = results.reshape((50,)) >>> year_results array([53, 28, 33, 23, 81, 58, 16, 6, 91, 84, 4, 20, 20, 27, 27, 82, 19, 76, 57, 47, 56, 97, 53, 21, 72, 18, 91, 29, 38, 15, 85, 20, 30, 67, 65, 1, 52, 95, 87, 70, 66, 70, 9, 30, 73, 1, 56, 29, 10, 76]) >>> year_results.shape (50,) >>> year_results.ndim 1 >>> year_results 53
The new array has one dimension, and that dimension's length is now 50. You just need a single index to access one of its values whenever you wish to access one of them.
The structure of a one-dimensional array is a tuple that contains a single element. When you require a 1D form, you may also use an integer as an input for the reshape() function.
>>> year_results = results.reshape(50) >>> year_results array([53, 28, 33, 23, 81, 58, 16, 6, 91, 84, 4, 20, 20, 27, 27, 82, 19, 76, 57, 47, 56, 97, 53, 21, 72, 18, 91, 29, 38, 15, 85, 20, 30, 67, 65, 1, 52, 95, 87, 70, 66, 70, 9, 30, 73, 1, 56, 29, 10, 76]) >>> year_results.shape (50,)
When you supply an integer argument for the newshape parameter, you receive the same result as when you pass a tuple with a single member. This is because both types of arguments are treated as integers. Note, however, that the.shape property is still a tuple with one element and not an integer. This is important to keep in mind.
You took the array from having two dimensions to having only one dimension, but you did not remove any of the data from the primary version.
Increase an Array’s Number of Dimensions
In this part of the lesson, you'll be working on a different example. A temperature sensor that records the current temperature of the home is placed by you and is set to record readings every three hours. The readings are compiled into a single-dimensional NumPy array that is produced by the sensor.
In this exercise, you will represent the temperature measurements with values chosen at random.
>>> import numpy as np >>> rng = np.random.default_rng() >>> temperatures = rng.normal(18, 1, size=200) >>> temperatures array([17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687, 17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, ... 18.17433295, 17.46510906, 18.30706081, 16.47186073, 14.49601283, 19.36982869, 18.78297168, 17.30458478, 18.40410989, 18.41390098, 16.77663847, 17.4153006 , 17.83923996, 18.77606957, 18.68240767]) >>> temperatures.shape (200,) >>> temperatures.ndim 1
A normal distribution is obtained by using the rng.normal() function. This distribution has a mean temperature of 18 degrees Celsius and a standard deviation of 1 degree Celsius. As the size parameter is a single integer rather than a tuple, the array that is produced as a result only has one dimension. In the next chapters of this guide, you will learn how to reformat this array into a variety of various configurations.
You need to reorganise the data in such a way that each 24-hour period is represented by its own row in the array. Due to the fact that the sensor records a value once every three hours, each row will contain a total of eight temperature measurements.
There are 200 readings in the temperatures array, which indicates that the reshaped array should have 25 rows, with each row holding eight values.
>>> temperatures_day = temperatures.reshape((25, 8)) >>> temperatures_day array([[17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687], [17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, 14.9819749 ], [17.09155469, 18.55311155, 17.82173679, 16.44808271, 18.33660455, 16.39911841, 17.46262617, 16.11580479], ... [19.27637947, 18.53564103, 18.7538117 , 17.28817758, 15.99178148, 16.7630879 , 18.25401129, 18.5474829 ], [17.46122335, 18.17433295, 17.46510906, 18.30706081, 16.47186073, 14.49601283, 19.36982869, 18.78297168], [17.30458478, 18.40410989, 18.41390098, 16.77663847, 17.4153006 , 17.83923996, 18.77606957, 18.68240767]]) >>> temperatures_day.shape (25, 8) >>> temperatures_day.ndim 2
The first eight temperature measurements from the original array have been moved to the first row of the newly reorganised array. The temperatures for the next eight days are recorded in the second row of the temperatures day table, and so on.
With this 2D array, it will be much simpler for you to get the data for a single twenty-four hour period. You might, for instance, get the data for the second day by using the temperatures day variable.
>>> temperatures_day array([17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, 14.9819749 ])
If you use the index 1, you will get the 1D array that is located in the second spot inside the temperatures day variable.
You increased the number of dimensions of the initial array from one to two by using the NumPy reshape() function. Nonetheless, you maintained the right order of the data throughout the process. In the next part, you will investigate what takes place in the event that the form of the new array is not compatible with the
Ensure the Shape of the New Array Is Compatible With the Original Array
You make the decision that in addition to organising your data by month, you would want to arrange it by week, and you want to reformat the array so that it has three rows.
- The first dimension represents the weeks.
- The second dimension represents the days within a week.
- The third dimension represents the individual readings within a day.
There are eight temperature measurements taken each day, and there are seven days in a week, therefore each week has a total of 56 temperature readings. As a consequence of this, the whole collection of 200 readings cannot be divided into an even number of weeks. There are three complete weeks, however there are additional readings that come from a portion of the fourth week.
You may make an effort to reshape the array such that it contains data for three weeks by sending the tuple (3, 7, 8) to the reshape() function. On the other hand, this will
>>> temperatures_week = temperatures.reshape((3, 7, 8)) Traceback (most recent call last): ... ValueError: cannot reshape array of size 200 into shape (3,7,8)
Since an array with form (3, 7, 8) includes 168 items, this results in an error being generated. This new array does not have enough room for the previous array, which had 200 items.
If the dimensions of the new array are compatible with those of the old array, then you are able to change the form of the array. You may reduce the total number of records in the original dataset to the first 168 of them in order to get an array with the form (3, 7, 8).
>>> days_per_week = 7 >>> readings_per_day = 8 >>> number_of_weeks = len(temperatures) // (days_per_week * readings_per_day) >>> number_of_weeks 3 >>> trimmed_length = number_of_weeks * days_per_week * readings_per_day >>> trimmed_length 168 >>> temperatures_week = temperatures[:trimmed_length].reshape( ... (number_of_weeks, days_per_week, readings_per_day) ... ) >>> temperatures_week array([[[17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687], [17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, 14.9819749 ], ... [18.56767078, 17.86123831, 18.81186461, 18.69086946, 18.45513019, 17.99669896, 18.20703493, 18.06268867], [17.11528709, 18.83735551, 16.49220439, 17.10466892, 17.88975427, 18.44527053, 16.71681421, 18.26859973]], [[18.24864303, 18.63744622, 18.80297891, 15.43544626, 18.29333932, 18.52391081, 17.09935544, 18.40424394], [17.64065163, 18.38806208, 18.40054375, 16.63639914, 17.8642428 , 19.04086886, 16.76040209, 17.87085502], ... [18.64131675, 18.21219446, 16.8594998 , 17.56934664, 17.17678561, 17.56550433, 18.51482721, 19.20758859], [19.24228543, 17.14736191, 18.30302811, 17.12356338, 18.31287005, 19.14701069, 17.53495458, 18.8801354 ]], [[18.154868 , 16.81175022, 19.22848909, 17.8604165 , 17.86463829, 19.11074667, 18.24322805, 16.54989167], [17.91524201, 19.32497959, 17.43219577, 18.17353934, 18.26306481, 19.27815777, 18.13648414, 18.27392718], ... [17.95081736, 17.24806278, 17.36949169, 17.43922213, 19.14574375, 17.5418501 , 17.26565033, 17.47016249], [16.12557219, 18.49384214, 19.53422956, 16.80504269, 17.31254144, 18.95745599, 19.46544502, 18.1389923 ]]]) >>> temperatures_week.shape (3, 7, 8) >>> temperatures_week.ndim 3
The number of dimensions of the initial array has been expanded from one to three as a result of your use of the reshape() function. In order to get the desired form, it was necessary, in this particular example, to eliminate some of the initial data.
You may choose to expand the original array rather than trim it if you don't want to throw away any of the data you've already collected. You will need to decide on a value in order to complete the expanded array with the extra places that have been added. In this demonstration, you will utilise NumPy's Not a Number constant, which is denoted by the notation.nan. This constant is appropriate to use because any numeric value that you provide might be interpreted as a temperature.
>>> extended_length = (number_of_weeks + 1) * ( ... days_per_week * readings_per_day ... ) >>> extended_length 224 >>> additional_length = extended_length - len(temperatures) >>> additional_length 24 >>> temperatures_extended = np.append( ... temperatures, np.full(additional_length, np.nan) ... ) >>> len(temperatures_extended) 224 >>> temperatures_extended array([17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687, 17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, ... 18.17433295, 17.46510906, 18.30706081, 16.47186073, 14.49601283, 19.36982869, 18.78297168, 17.30458478, 18.40410989, 18.41390098, 16.77663847, 17.4153006 , 17.83923996, 18.77606957, 18.68240767, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan])
You must first determine how many new values must be added to the array before it will contain a complete number of weeks. The addition of an array containing np.nan values to the temperatures array using the np.append() function produced the expanded array temperatures extended as a consequence. You can create the array containing np.nan values by using the np.full() function.
You are now able to reform the extended array into the form that you require in order to have four weeks of
>>> temperatures_week = temperatures_extended.reshape( ... (number_of_weeks + 1, days_per_week, readings_per_day) ... ) >>> temperatures_week array([[[17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687], [17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, 14.9819749 ], ... [ nan, nan, nan, nan, nan, nan, nan, nan], [ nan, nan, nan, nan, nan, nan, nan, nan]]]) >>> temperatures_week.shape (4, 7, 8) >>> temperatures_week.ndim 3
The new array that we've created, called temperatures week, now has the shape (4, 7, 8). Since there were no temperature readings for the final week in the array, those values were replaced with the value np.nan.
When you wish to reshape an array into a new form that is not compatible with the original one, you will need to determine whether you want to trim an array or extend it with filler. If you choose to trim the array, you will need to decide how much filler to add.
Control How the Data Is Rearranged Using
In every one of the examples that you've worked on up to this point, the reshaped arrays have always had the data set up in the appropriate manner. For instance, the first eight values of the 1D array temperatures were reorganised such that they would appear in the first row of the 2D array temperatures day. This first row summarises the data collected on the first day of the collecting process.
There will be situations in which the reconfigured default configuration does not meet the criteria that you have specified. In this portion of the course, you will see an example of this scenario, and you will also learn how to utilise the optional parameter order in NumPy's reshape() to acquire the configuration that you want.
When you reshape an array, you have the ability to choose how the data is rearranged by using the order argument, which is an optional part of the reshape() function. This parameter's argument may be "C," "F," or "A," and it can take any of those three values. You may begin by constructing a basic array, and after that, investigate the first two of these options.
>>> import numpy as np >>> numbers = np.array([1, 2, 3, 4, 5, 6, 7, 8]) >>> numbers array([1, 2, 3, 4, 5, 6, 7, 8]) >>> numbers.shape (8,) >>> numbers.ndim 1 >>> numbers.reshape((2, 4), order="C") array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> numbers.reshape((2, 4), order="F") array([[1, 3, 5, 7], [2, 4, 6, 8]])
Each of the new arrays have a total of four columns and two rows. On the other hand, the components are reorganised into a variety of various configurations.
"C" and "F" in a string argument are shorthand for the programming languages "C" and "Fortran," respectively. The array indexing used by these languages is distinct from one another.
C uses the
Fortran uses the
These phrases were initially used to describe the manner in which items of an array were kept in memory. To be more specific, the memory configuration is irrelevant regardless of whether "C" or "F" is used as an argument for order. The order in which the indices are listed indicates the order in which each member of the array is to be accessed. One way to think about this is as the order in which one would list all of the components in a list.
In the arrangement known as row-major order, the components are listed in sequential order along the rows. After you have completed this row, you will go on to the next row and start at the beginning of that row.
In the order known as column-major order, the sequence of components moves from left to right across the columns in ascending order. As soon as you get to the bottom of one column, you'll start again at the very beginning of the following column.
The distinction between the two may be seen more clearly in the following diagram:
This figure illustrates how the components of a two-dimensional array may be arranged in a variety of ways. You may apply the same technique to arrays with a higher dimension if you want to.
When you supply "C" as a parameter for order in the example that was just shown, the items from the first array are copied into the second array using the C-like order, also known as the row-major order. The first row of the newly created array is taken up by the first four entries. As soon as the objects in the first row are used up, the ones left behind begin filling the second row.
Hence, when order="C" is used with reshape(), the function changes the eight members of the old array to the new array in the following order of indices:
When you use indexing that is similar to C, the indices will be ordered as shown in this figure.
When using reshape(), the final axis is the one that may be changed the fastest in response to components being read or written. The first index does not change until a row has a total of four items, but the final index is updated after each consecutive element.
reshape() employs the Fortran-like order, often known as the column-major order, when the "F" option is passed to it. The columns are completed before the rows.
Consequently, when order="F" is used with reshape(), the function changes the eight members of the old array to the new array in the following order of indices:
When you use indexing that is similar to Fortran, the indices will be ordered as shown in this figure.
In this particular scenario, the first index is changing at a quicker rate since it is being updated for each succeeding element. As each column is finished, the second index is updated accordingly.
Although the various indexing orders initially represented the memory configuration of the array, the result of reshape() is not dependent on the actual memory configuration when "C" and "F" are used as arguments for order. This is because the result of reshape() is independent of the actual memory configuration.
In addition to choices "C" and "F," there is also a third alternative. If you tell the order argument that you want the index order to match the memory layout of the array, then you must supply "A" to the order parameter. Since you depend on the NumPy package to take care of these specifics for you, you probably aren't aware of the memory layout of the arrays that are included inside your programme. This is because the NumPy package handles this aspect of the programming for you. Using NumPy has several advantages, and this is one of them. As a result, "C" and "F" are the lines of reasoning that you are most likely to adopt.
Reduce a Three-Dimensional Color Image to Two Dimensions
In this part of the tutorial, you will read a colour picture into a three-dimensional NumPy array and then construct a triptych that displays the red, green, and blue components of the image side by side in a two-dimensional representation.
You will be reading the picture and converting it to a NumPy array with the help of the Pillow library. Using the use of pip, the library might be installed into your virtual environment.
(venv) PS> python -m pip install Pillow
(venv) $ python -m pip install Pillow
If you like, you may use a photograph that you have taken yourself rather than the poppy.jpg file that is included with this lesson (image credit). You will need to move the file into the folder for the project that you are currently working on. If you would like to make use of the picture that has been supplied, then please download the additional resources by clicking the following link:
To begin, read the picture file with the Pillow library and then convert the data to a NumPy array. You can have the option of displaying the picture by using
>>> import numpy as np >>> from PIL import Image >>> with Image.open("poppy.jpg") as photo: ... image_array = np.array(photo) ... >>> photo.show() >>> image_array.shape (769, 1280, 3) >>> image_array.ndim 3
The picture will be shown by the application that is set as your default for viewing photos when the photo.show() function is called:
When you use the photo variable as an argument to the np.array() function, the picture is transformed into a three-dimensional NumPy array. The first two dimensions specify the image's width and height in terms of the number of pixels used. The colours red, green, and blue are each represented by a channel in the third dimension. It's possible that some photographs will additionally have the alpha value included in the third dimension.
You want to turn this 3D array into a 2D picture with the same height as the original image but three times the breadth. This will allow you to show the red, green, and blue components of the image in a manner that is more aesthetically pleasing. See the results of reshaping the three-dimensional array now. You may get the image's height and breadth in pixels by unpacking the image array.shape and ignoring the third parameter.
>>> height, width, _ = image_array.shape >>> height 769 >>> width 1280 >>> triptych = image_array.reshape((height, 3 * width)) >>> triptych.shape (769, 3840) >>> triptych.ndim 2 >>> Image.fromarray(triptych).show()
The picture is shown after the three-dimensional array is reorganised into a two-dimensional format. Nonetheless, this is not the impression that you were hoping to convey:
The letter "C" is used as the default parameter for order. As the 3D array is being reorganised, this indicates that reshape() makes the most rapid modifications to the final axis. The three different colour channels are represented by the final axis of the diagram.
So, while creating the new array, reshape() will first take the value from the red channel of the pixel that is located in the top-left corner of the picture. After that, it takes the value from the green channel for the same pixel and sets it next to the value from the red channel. The value that corresponds to the blue channel in the first pixel of the primary colour picture is the next item in the newly created array.
The first pixel of the new colour picture was used to create the first three pixels of the first row of the new image. The original colour image had just one pixel. The horizontal dimensions of each pixel in the picture are expanded using the red, green, and blue values of the pixel.
You will be able to notice this if you use the.crop() function from the Pillow library to zoom in on a specific area of the picture.
>>> Image.fromarray(triptych).crop((400, 300, 500, 400)).show()
You may choose a tiny portion of the original picture by using the.crop() function. This displays a portion of the picture that includes a portion of a bright red blossom as well as a blue sky:
The section of the picture that depicts the flower has a strong red component, in contrast to the area of the picture that depicts the sky, which features a strong blue component. As you walk down a column in this cropped picture from top to bottom, you'll see that the values that are the brightest change to the side as you move from the area of the image that contains the sky to the portion that contains the flowers.
The fact that each pixel in the original picture is represented by its red, green, and blue components next to one another in this reshaped form of the 2D image is shown by this observation.
You would obtain a different picture, however, if reshape() followed a different sequence and the third axis was the one that was adjusted at the very end of the process. This is the index order that is similar to Fortran, and you may get it by giving the letter "F" to the order function.
>>> triptych = image_array.reshape((height, 3 * width), order="F") >>> Image.fromarray(triptych).show()
When you make a call to reshape(), you pass in the letter "F" as an argument. Now the picture has all three colour channels laid out next to one another:
The image on the left displays the red channel that was present in the original picture. The pixels that depict the flower petals are the ones that are the brightest in the image. In the first version of the photograph, these petals are coloured red. This picture may be compared to the one on the right, which is the blue channel. The areas of the picture that display the sky are represented by the pixels with the highest level of brightness, while the pixels that depict the petals have a lower level of brightness in the blue channel.
You have seen how the order in which you reshape an array may have a major influence on the final output via the use of this example. When reshaping a NumPy data set, you may influence how the data is rearranged by making use of the order option in the reshape() function.
You have consistently included the lengths of all the dimensions in the reshaped array in every single one of the instances that you have used throughout this course. Nevertheless, if you want to, you can add a wildcard option for one of the dimensions and let reshape() figure out how long the rest of the information is by looking at the length of the wildcard option.
You have the option of making use of the same temperatures array that you used previously, or you may generate a whole new one if you are operating in a different REPL.
>>> import numpy as np >>> rng = np.random.default_rng() >>> temperatures = rng.normal(18, 1, size=200) >>> temperatures array([17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687, 17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, ... 18.17433295, 17.46510906, 18.30706081, 16.47186073, 14.49601283, 19.36982869, 18.78297168, 17.30458478, 18.40410989, 18.41390098, 16.77663847, 17.4153006 , 17.83923996, 18.77606957, 18.68240767]) >>> temperatures.shape (200,)
Every twenty-four-hour period is divided into eight readings. Before, you performed a manual division of 200 by 8, which led to the conclusion that the reshaped array need to include 25 rows.
On the other hand, when determining the length of the first dimension, you may use the number -1.
>>> temperatures_day = temperatures.reshape((-1, 8)) >>> temperatures_day array([[17.78916577, 18.48720738, 17.16745854, 18.63306583, 18.30034365, 18.36342512, 18.37339031, 19.22000687], [17.14534477, 15.90837538, 17.37115548, 17.68445145, 19.20665509, 16.86856826, 19.15139203, 14.9819749 ], [17.09155469, 18.55311155, 17.82173679, 16.44808271, 18.33660455, 16.39911841, 17.46262617, 16.11580479], ... [19.27637947, 18.53564103, 18.7538117 , 17.28817758, 15.99178148, 16.7630879 , 18.25401129, 18.5474829 ], [17.46122335, 18.17433295, 17.46510906, 18.30706081, 16.47186073, 14.49601283, 19.36982869, 18.78297168], [17.30458478, 18.40410989, 18.41390098, 16.77663847, 17.4153006 , 17.83923996, 18.77606957, 18.68240767]]) >>> temperatures_day.shape (25, 8)
You are going to supply a tuple with the value -1 as the first member of it. It is impossible for a negative integer to represent a length that is valid for a dimension. The number -1 is sent to the reshape() function so that it may determine the length of the remaining dimension on its own. You are free to use any negative integer as a wildcard value, but the manual recommends that you use -1 instead since it is more reliable.
Just one of the dimensions may be changed to -1 in this calculation. If you include -1 more than once, you will get an error.
>>> temperatures_day = temperatures.reshape((-1, -1)) Traceback (most recent call last): ... ValueError: can only specify one unknown dimension
This line of code causes a ValueError to be thrown because the argument that you provide to the reshape() function has multiple occurrences of the value -1. There is not enough information to make an educated guess about the length of either of the two dimensions that are unknown.
Flattening an array with any number of dimensions may be accomplished with the help of this wildcard option. When an array is reduced to a single element, this action is referred to as "flattening."
>>> rng = np.random.default_rng() >>> numbers = rng.integers(1, 100, (2, 4, 3, 3)) >>> numbers.shape (2, 4, 3, 3) >>> numbers.ndim 4 >>> numbers_flattened = numbers.reshape(-1) >>> numbers_flattened array([76, 58, 14, 44, 15, 28, 19, 12, 18, 26, 64, 82, 20, 85, 54, 80, 26, 18, 90, 24, 9, 61, 40, 55, 14, 81, 53, 33, 26, 40, 70, 50, 94, 46, 30, 21, 58, 71, 79, 84, 67, 34, 93, 71, 94, 68, 59, 85, 78, 82, 9, 36, 28, 76, 78, 27, 4, 46, 24, 99, 96, 82, 60, 67, 40, 63, 5, 69, 15, 69, 11, 97]) >>> numbers_flattened.shape (72,) >>> numbers_flattened.ndim 1
You create a new array and give it the name numbers. It has four dimensions. The confirmation of the number of dimensions may be found in the numbers.ndim attribute. The array that has been flattened is a one-dimensional array that is 72 elements long. The length of the new one-dimensional array may be calculated by multiplying the lengths of the original array's four dimensions together.
Because you do not need to know the length of one of the dimensions of the reshaped array, you can make your code more flexible by using the value -1. This is because you do not need to know the length of one of the dimensions.