Academia Master Trader

Laboratórios de leitura de gráficos e conceitos financeiros. Projeto educacional brasileiro. Exemplos fictícios, sem recomendação de investimento.

NumPy select applies ordered conditions and uses the first matching choice at each position

Several conditions can describe alternative ways to fill an output array. NumPy select pairs each condition with a choice and gives priority to the first matching condition at each position. Academia Master Trader explains this rule in English for readers in Kazakhstan. Constructed examples show how overlaps, defaults and list order determine the result. Writing the rules down makes the selection easier to follow than looking only at the final values.

Pair conditions with their choices

After import numpy as np, define x = np.array([1,3,5,7]). Set conditions = [x < 4,x > 6] and choices = [x * 10,x + 100]. The call np.select(conditions,choices,default=-1) returns [10,30,-1,107]. The first condition selects ten times x, and the second selects x plus one hundred.

At values one and three, the first condition is true, so their outputs are ten and thirty. At five, neither condition is true, so the output is the default minus one. At seven, the second condition is true, producing one hundred and seven. The condition list and choice list must contain the same number of entries.

NumPy select

The first true condition has priority

Now set conditions = [x < 6,x > 2], while retaining the same choices. The call np.select(conditions,choices,default=-1) returns [10,30,50,107]. At three and five, both conditions are true. The first condition supplies the output, so those positions use ten times x rather than x plus one hundred.

The function does not combine the matching choices or select the largest numerical result. It uses list order as the priority rule. This matters when two conditions overlap even if the example appears to describe separate categories. Inspect their Boolean arrays directly instead of assuming that every position can satisfy only one condition.

Reordering changes the priority rule

If the condition and choice pairs are reversed together, the overlap is handled differently. The expression np.select([x > 2,x < 6],[x + 100,x * 10],default=-1) returns [10,103,105,107]. At three and five, the condition naming x plus one hundred is now encountered first.

Keep each condition beside its matching choice when changing order. Reordering only one list changes the pairing as well as the priority and can express a different rule from the one intended. A short written mapping, such as less than six means ten times x, helps preserve the relationship between each condition and its output.

A default covers positions with no match

The default argument supplies an output wherever every condition is false. If it is omitted, the documented default is zero. For the initial conditions, np.select([x < 4,x > 6],[x * 10,x + 100]) returns [10,30,0,107]. The zero at the position containing five comes from that default.

An output value alone does not reveal whether it came from a choice or the default, particularly when a choice can produce the same value. Retain the conditions and rule description when that distinction matters. A default is part of the selection design, not evidence that the corresponding source value was zero or missing.

Read each output through the ordered rules

Select fills the output position by position using the supplied condition and choice pairs. In these examples, x retains its original values. The transformed numbers belong to the constructed output; they do not replace the source merely because the rule mentions x.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Check the pairings, inspect overlaps and state the default explicitly. Then trace each result back to the first true condition. This keeps a multi condition selection understandable without assigning hidden meaning to its priority order.

NumPy choose uses integer codes to select from corresponding positions in choice arrays

Selecting from several arrays requires a rule about which array supplies each output entry. NumPy choose uses integer codes to express that rule. Academia Master Trader explains the operation in English for readers in Azerbaijan. Constructed examples show how a code selects a source array while the output position determines which entry is taken from that source. This is different from simply retrieving positions within one vector.

Match each code to a choice array

After import numpy as np, define low = np.array([10,20,30]) and high = np.array([100,200,300]). The expression np.choose([0,1,0],[low,high]) returns [10,200,30]. Code zero names low, the first choice array. Code one names high, the second choice array.

At output position zero, code zero selects low's entry at position zero, which is ten. At position one, code one selects high's entry at position one, which is two hundred. At position two, code zero selects low's entry at position two, which is thirty. Both the code and the position matter.

NumPy choose

A code does not name an entry within one vector

The codes [0,1,0] do not mean to retrieve positions zero, one and zero from low. They identify which member of the choice sequence supplies the value at each output position. This distinction explains why the final entry is thirty rather than ten in the example above.

Keep the choices in an explicit list or tuple. The sequence order establishes the meaning of each integer code. Reversing the choices while leaving the code array unchanged changes the selection rule. For example, np.choose([0,1,0],[high,low]) returns [100,20,300]. Document the code mapping beside the data instead of assuming that zero always names a particular category.

Scalar choices can fill a shaped code array

The call np.choose([[0,1],[1,0]],[5,9]) returns [[5,9],[9,5]]. Each scalar choice is broadcast across the shape of the code array. Zero selects five and one selects nine at each of the four positions. The resulting array has shape (2,2).

The code array and every choice must be broadcastable to a common shape. Equal shapes satisfy that requirement, but they are not the only possibility, as the scalar example shows. Check the common shape when using more complicated inputs. An unexpected shape can change the arrangement of the output even when the code values look familiar.

Default mode requires valid choice codes

With two choices, the valid codes in the default mode are zero and one. A code of two is outside that range and raises an error. The upper limit depends on the number of choices, not on the number of entries within each choice array.

For the three entry low and high arrays, np.choose([0,2,1],[low,high],mode='wrap') returns [10,20,300]. Wrap maps code two back to zero because there are two choices. The same call with mode clip returns [10,200,300], since clipping maps code two to the highest valid code, one. Choose the boundary rule deliberately rather than treating these modes as interchangeable corrections.

Read the result through its source mapping

A selected value remains the entry from its chosen source at the corresponding position after broadcasting. Choose does not average the alternatives or combine their magnitudes. The output is an arrangement governed by the supplied codes, choice sequence and boundary mode.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the code mapping, common shape and mode. Trace a few output positions back to their source entries. This makes the selection understandable without assigning extra meaning to the numerical codes themselves.

NumPy extract gathers entries selected by a condition into a one dimensional array

A condition can select individual entries from a matrix without keeping its original row and column arrangement. NumPy extract returns those selected values as a one dimensional array. Academia Master Trader explains the operation in English for readers in Armenia. Constructed examples show how a condition maps to positions, how the output order is determined and why a selected vector is not a smaller rectangular version of the original matrix.

Apply a condition to a small matrix

After import numpy as np, define m = np.array([[2,5,8],[11,14,17]]). This matrix has two rows and three columns. The comparison condition = m > 9 produces [[False,False,False],[True,True,True]]. Each Boolean entry describes whether the value at that same position is greater than nine.

The call np.extract(condition,m) returns [11,14,17]. It gathers the three values marked true and places them in a vector. The result has shape (3,), not (1,3). Although the selected values came from one row in this particular example, extract does not retain that row dimension.

NumPy extract

Selection can cross row boundaries

Consider condition = m % 2 == 0. The remainder calculation identifies even values, giving [[True,False,True],[False,True,False]]. The expression np.extract(condition,m) returns [2,8,14]. These selected entries come from different rows and columns, yet the output is still one dimensional.

The function follows the flattened input sequence, which here is [2,5,8,11,14,17]. It keeps the entries whose corresponding condition positions are true. The order is therefore two, eight and fourteen. It does not group entries by column or sort them as a separate operation. Any numerical ordering in this example comes from the original arrangement.

Think of values and condition being flattened together

The documented operation is equivalent to applying compress to the flattened condition and the flattened source array. For the even value example, the condition sequence is [True,False,True,False,True,False]. Applying it to the flattened values retrieves exactly the same three entries.

Use an input and condition with the same number of entries, as the interface specifies. A Boolean condition with the same shape as the input is usually easiest to read because each position aligns visibly. Write the condition from the intended rule, then inspect it beside the source instead of assuming it selects the entries you had in mind.

Numerical conditions select nonzero positions

The condition can also contain numerical entries. Nonzero entries indicate positions to retain, while zero entries indicate positions to omit. For example, np.extract([0,2,0,-1],[10,20,30,40]) returns [20,40]. The two and minus one act as selection signals; they do not multiply the retrieved values.

A Boolean condition is often clearer when explaining a filtering rule, because true and false state the choice directly. If numerical conditions are used, explain their nonzero interpretation so that readers do not mistake their magnitudes for weights. A retained entry remains the original value from its source position.

Keep the selection distinct from the source

The source matrix still contains all six original entries after extraction. The returned vector describes the subset selected by the stated condition. Its shorter length does not establish that omitted entries were invalid, unavailable or absent from the source. Those interpretations would require information beyond the selection itself.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape and the rule used to build the condition. Check which positions are true and confirm the one dimensional output. This keeps array filtering clear without turning a selection rule into an unsupported conclusion about the underlying data.

NumPy compress selects array slices where a one dimensional condition is true

A Boolean condition can describe which positions to keep from an array. NumPy compress uses a one dimensional condition to select slices along a chosen axis. Academia Master Trader explains this operation in English for readers in Georgia. Constructed vectors and matrices show the relationship between condition positions, retained entries and output shape. Selecting a subset changes which entries are present, not the meaning of the original observations.

Keep the entries marked true

After import numpy as np, define x = np.array([12,24,36,48]). The call np.compress([True,False,True,False],x) returns [12,36]. Positions zero and two are kept because the corresponding condition entries are true. Positions one and three are omitted because their condition entries are false.

The condition follows positions in the input. It does not name the numerical values to retrieve, and it does not arrange the retained entries by size. The selected entries appear in their original sequence. Reading the condition beside the input is a simple way to check which positions contribute to the result.

NumPy compress

Select complete rows with axis zero

Define m = np.array([[1,2],[3,4],[5,6]]), with shape (3,2). The expression np.compress([True,False,True],m,axis=0) returns [[1,2],[5,6]]. Each true condition entry retains a complete row. The middle row is omitted, and the result has shape (2,2).

The condition has three positions because the selected row dimension has length three. Two true entries produce two retained rows. The other dimension still has length two, because the selection retains both columns within every selected row. Counting true entries helps predict the output length along the selected axis.

Select columns with axis one

The call np.compress([False,True],m,axis=1) returns [[2],[4],[6]]. This condition addresses the two column positions. Only the second column is retained, so the output has shape (3,1). All three rows remain in the result.

A two dimensional result with one column is different from a one dimensional vector. The brackets show that each retained entry still belongs to a row containing one column. State the output shape when explaining this selection so that a later calculation does not silently assume a different number of dimensions.

A missing axis means a flattened selection

With no axis argument, compress works on the flattened input. For the matrix m, the call np.compress([False,True],m) returns [2]. The flattened sequence begins with one and two. The two entry condition addresses those first two positions, keeping only the second.

This example also illustrates a documented detail: when the condition is shorter than the selected dimension, only the positions covered by the condition participate. The remaining positions are not selected automatically. Prefer a condition that matches the intended axis length when you want to make a decision about every position, and check the lengths explicitly.

The output is a copy

Compress returns a copy rather than a view of the selected slices. For example, create selected = np.compress([True,False,True,False],x). Setting selected[0] = 99 changes the first entry of selected, while the original x still begins with twelve. This behavior differs from operations that return views sharing the source storage.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the condition, its length and the selected axis before filtering. Inspect the output shape and retained positions afterward. This keeps selection rules visible without treating an omitted entry as if it never existed in the source array.

NumPy take selects array entries in the order specified by integer positions

A list of positions can describe a deliberate selection from an array. NumPy take retrieves entries in that requested order, including repeated positions when they appear in the index list. Academia Master Trader explains the operation in English for readers in Ukraine. Small constructed vectors and matrices show how axis selection changes the meaning of a position and how an index array can shape the output.

Select positions rather than numerical values

After import numpy as np, define x = np.array([10,20,30,40]). The call np.take(x,[3,0,3]) returns [40,10,40]. Position three supplies forty, position zero supplies ten and the repeated position three supplies forty again. The function follows the index sequence rather than sorting the selected values.

Python uses zero based indexing here: the first entry is at position zero. The list [3,0,3] names positions, not the values three and zero. Repetition in the result comes from repetition in the selection. It does not mean that the original vector has gained another independently recorded entry.

NumPy take

Select columns with an explicit axis

Define m = np.array([[1,2,3],[4,5,6]]), which has shape (2,3). The expression np.take(m,[2,0],axis=1) returns [[3,1],[6,4]]. It selects column position two and then column position zero while keeping both rows. The result has shape (2,2).

With np.take(m,[1,0],axis=0), the result is [[4,5,6],[1,2,3]]. This selection requests row position one before row position zero. The numerical index one has a different role depending on the selected axis. Write both the axis and the intended positions when explaining a matrix selection.

Omitting the axis uses a flattened input

The call np.take(m,[2,0]) returns [3,1]. With the default axis value of None, take treats the input as flattened instead of selecting complete columns. In this example, the flattened sequence is [1,2,3,4,5,6]. Positions two and zero therefore retrieve three and one.

Compare that one dimensional result with the two dimensional column selection made using axis one. The same index list can produce different shapes and groupings because the axis setting defines the selection context. Include that setting in a reusable example rather than relying on a reader to infer it from the returned numbers.

The index array can have its own shape

For the original vector x, np.take(x,[[0,2],[3,1]]) returns [[10,30],[40,20]]. The two by two arrangement of indices produces a two by two arrangement of selected entries. Each index supplies one value from the vector at the corresponding output position.

For a general axis selection, the index array's dimensions replace the selected axis in the output shape. Dimensions before and after that axis remain around them. For example, applying that two by two index array to the columns of a two row matrix would add both index dimensions between the retained row dimension and any dimensions that follow the selected axis.

Decide how outside positions should behave

The default mode raises an error for an index outside the valid range. The mode named wrap maps indices around the axis length. The mode named clip restricts them to the range endpoints. For x, np.take(x,[4],mode='wrap') returns [10], while np.take(x,[4],mode='clip') returns [40].

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, selected axis, index sequence and boundary mode. Check output shape as well as values. These details explain the selection without confusing repeated retrieval with additional source data.

NumPy array split divides uneven lengths into sections that differ by at most one entry

An array does not always divide evenly into the requested number of sections. NumPy provides array split for that situation. With an integer section count, it distributes entries into equal or near equal sections while preserving their sequence along the chosen axis. Academia Master Trader explains this behavior in English for readers in Belarus. Constructed examples show where the longer sections appear and why a requested section count differs from a desired section length.

Eight entries divided into three sections

After import numpy as np, define x = np.array([2,4,6,8,10,12,14,16]). The call parts = np.array_split(x,3) returns [2,4,6], [8,10,12] and [14,16]. These sections have lengths three, three and two. Every input entry appears once in this division, and the original order remains unchanged.

The number three means the number of sections. It is not the maximum length of a section. When designing a workflow that needs a fixed maximum number of entries per section, work out the required section count separately instead of assuming that this argument expresses that limit.

NumPy array split

The remainder goes to the first sections

Let the selected axis have length L and let N be the positive integer number of sections. Integer division gives the base section length. The remainder tells you how many sections need one additional entry. Array split places those longer sections first, followed by the sections with the base length.

For eight entries and three sections, the base length is two and the remainder is two. Therefore, the first two sections contain three entries each and the last contains two. For nine entries divided into four sections, the lengths are three, two, two and two. Section lengths differ by at most one when the integer count form is used.

More sections than entries can produce empty arrays

Consider y = np.array([7,9]). The expression np.array_split(y,4) returns four arrays: [7], [9], [] and []. Two entries cannot populate four nonempty sections. Returning the requested number of sections therefore includes empty arrays in this example.

The base section length is zero and the remainder is two. That produces two sections with one entry and two sections with zero entries. Check section sizes before later operations that expect a nonempty input. Do not interpret an empty section as an extra observed value or insert a made up entry to hide it.

Axis selection also works for matrices

Define m = np.array([[1,2,3,4,5],[6,7,8,9,10]]), with shape (2,5). The call np.array_split(m,3,axis=1) divides the five column positions into widths two, two and one. The results are [[1,2],[6,7]], [[3,4],[8,9]] and [[5],[10]].

Their shapes are (2,2), (2,2) and (2,1). Both rows remain present in each section because the operation divides axis one. Selecting axis zero instead would divide the two row positions. Always calculate section sizes from the selected dimension's length, rather than from the total number of entries in the matrix.

Choose the division rule explicitly

For the eight entry vector, np.split(x,3) raises ValueError because its integer form requires equal division. Array split accepts the same section count and distributes the remainder. The distinction is a rule about section sizes, not a change to the numerical values stored in x.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the axis length, section count, base length and remainder before dividing. Inspect the output shapes afterward, including any empty sections. A clear division rule keeps the structure of each section explicit without inventing new data.

NumPy split divides an array into sections along a chosen axis

Dividing an array into sections begins with a question about boundaries. Do you want a fixed number of equally sized pieces, or pieces that end at specific positions? NumPy split supports both forms. Academia Master Trader explains the distinction in English for readers in Andorra. The examples use constructed arrays so that section sizes, entry order and axis choices can be checked directly.

An integer specifies the number of sections

After import numpy as np, define x = np.array([2,4,6,8,10,12]). The call parts = np.split(x,3) produces three arrays: [2,4], [6,8] and [10,12]. The integer three asks for three equal sections. It does not ask for sections containing three entries each.

The input length is six, and six divides equally into three sections of length two. The default axis is zero. For this one dimensional array, that axis follows the vector's single dimension. The returned object is a list of arrays, so parts[0] selects the first section and parts[2] selects the third.

NumPy split

A sequence specifies boundary positions

The expression np.split(x,[1,4]) returns [2], [4,6,8] and [10,12]. Positions one and four mark boundaries, using zero based indexing. The corresponding slices are x[:1], x[1:4] and x[4:]. The boundary entry belongs to the next section, rather than to the section that ends there.

Here, the sections have different lengths because explicit positions define the boundaries. Two boundary positions produce three sections. Use a sorted sequence of integer positions when this is the intended form. Before running the operation, write the implied slices to make the boundary interpretation clear, particularly when values happen to resemble their own positions.

Equal sections need equal division

With the six entry vector, np.split(x,4) cannot make four equal sections and raises ValueError. Split does not quietly distribute extra entries among the pieces when its second argument is an integer. The integer form and the boundary sequence form therefore express different requirements, not interchangeable ways of requesting approximate chunk sizes.

NumPy also provides a related function named array split for equal or near equal sections when division is uneven. Choose that behavior deliberately if the task allows section lengths to differ. Do not describe an uneven division as an equal one merely because every input entry appears somewhere in the result.

The chosen axis determines the direction

Define m = np.array([[1,2,3,4],[5,6,7,8]]), which has shape (2,4). The call np.split(m,2,axis=0) returns two arrays with shape (1,4). The first contains the first row, and the second contains the second row. Both retain two dimensions.

With np.split(m,2,axis=1), the results are [[1,2],[5,6]] and [[3,4],[7,8]]. Each has shape (2,2). The operation divides the column dimension while keeping both rows in each section. Axis choice describes a dimension of the input, so check that dimension's length before deciding whether equal division is possible.

Sections can share the original data

The returned sections are views into the original array. They should not be treated as independent copies. For example, after creating parts from x as above, assigning parts[0][0] = 99 also changes the first entry of x to ninety nine. Use a copy of a section when independent storage is required for later changes.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the selected axis, its length and whether the second argument names sections or boundaries. Then inspect the resulting shapes and consider whether shared storage is suitable for the next operation.

NumPy stack joins equal shaped arrays by introducing a new dimension

Combining arrays can preserve each input as a separate slice instead of extending an existing dimension. NumPy stack does this by introducing a new axis. Academia Master Trader explains the operation in English for readers in Vatican City. Small constructed vectors and matrix shapes make the distinction visible. The examples focus on how input order and the position of the new axis determine the output arrangement.

Two vectors can become two rows

After import numpy as np, define x = np.array([2,4,6]) and y = np.array([3,5,7]). Both inputs have shape (3,). The call np.stack((x,y)) returns [[2,4,6],[3,5,7]]. The output has shape (2,3): two input arrays are arranged along a newly created first axis.

The first output row contains x and the second contains y. Within each row, the original entry order is preserved. The default axis is zero, so np.stack((x,y),axis=0) gives the same result. The new dimension identifies which input array supplied the corresponding slice, according to the order in the supplied sequence.

NumPy stack

Put the new dimension at the end

The call np.stack((x,y),axis=1) returns [[2,3],[4,5],[6,7]]. The output shape is (3,2). Each row pairs entries at the same position in the two original vectors. Two is paired with three, four with five and six with seven.

For these one dimensional inputs, axis minus one selects that same final position for the new dimension. Thus np.stack((x,y),axis=-1) gives the same result as axis one. This equality depends on the dimensions of the result. State where the new axis appears instead of assuming that the same axis number has a universal row or column meaning.

Equal shape is a requirement

Every input array in the sequence must have the same shape. A vector with three entries and a vector with two entries do not meet that requirement. Stack does not automatically fill the shorter vector or repeat its entries to make it fit. Decide the intended representation before combining unequal inputs.

Matching total entry counts is also not enough if shapes differ. A matrix with shape (2,3) and one with shape (3,2) both contain six entries, but they are not equal shaped inputs. Write the complete shapes down before stacking, including every dimension length rather than just the total size.

Matrices gain a third dimension

Suppose p and q are two matrices, each with shape (2,3). The expression np.stack((p,q),axis=0) has shape (2,2,3). The new first dimension has length two because there are two input matrices. Each slice selected along that dimension has the original two by three shape.

With axis one, the result has shape (2,2,3) as well, but the new dimension occupies a different position. Equal printed shapes do not guarantee equal arrangements when two dimension lengths happen to match. With axis two, the result has shape (2,3,2), placing the input selection dimension last. Trace a specific entry when dimension lengths alone cannot distinguish the layouts.

A new axis differs from a longer existing axis

For the vector example, np.concatenate((x,y)) returns [2,4,6,3,5,7], a vector with six entries. Stack instead returns a two dimensional result. Both operations preserve the supplied numbers and input order, but they encode the grouping differently in the output shape.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record each input shape, the input sequence and the position of the new axis. Then check that the output has one more dimension than an individual input array. This makes array grouping explicit without turning a new layout into new information.

NumPy concatenate joins arrays along an existing axis with matching other dimensions

Joining arrays requires a rule about where the entries should meet. NumPy concatenate joins a sequence of arrays along an axis that already exists. Academia Master Trader explains the operation in English for readers in San Marino, using small constructed arrays. The examples keep the join direction and shape requirements visible, so the resulting arrangement is clear before any numerical interpretation is made.

Join two vectors in their supplied order

After import numpy as np, define x = np.array([2,5]) and y = np.array([8,11,14]). The call np.concatenate((x,y)) returns [2,5,8,11,14]. The entries from x come first, followed by the entries from y. The output remains one dimensional and has five entries.

The function does not sort, alternate or combine the numbers arithmetically. Reversing the input sequence to np.concatenate((y,x)) returns [8,11,14,2,5]. Input order is therefore part of the result. Write down that order when explaining the join rather than describing the output as an unordered collection.

NumPy concatenate

Join rows along the first axis

Define a = np.array([[1,3],[5,7]]) and b = np.array([[9,11]]). The call np.concatenate((a,b),axis=0) returns [[1,3],[5,7],[9,11]]. The first array has two rows, the second has one, and both have two columns. The result has three rows and two columns.

The row counts can differ because axis zero is the dimension being joined. The column counts must match in this example. Each complete row from b can then follow the rows from a without leaving an undefined position in the rectangular output. The default axis is zero, so omitting the axis gives the same result here.

Join columns when the row counts match

Define c = np.array([[9],[11]]). The call np.concatenate((a,c),axis=1) returns [[1,3,9],[5,7,11]]. Both inputs have two rows. The first has two columns and the second has one, giving an output with two rows and three columns.

Although b and c contain the same two numerical values, their shapes are different. The one row shape of b suits the earlier vertical join, while the one column shape of c suits this horizontal join. Values alone do not determine compatibility. Check each input's number of dimensions and the lengths outside the selected join axis.

Flatten explicitly with axis None

The call np.concatenate((a,b),axis=None) returns [1,3,5,7,9,11]. With axis None, the input arrays are flattened before being joined. The output is a single vector rather than a matrix with three rows.

This setting can be useful when only the sequential entries are needed, but it removes the row grouping from the output shape. State that transformation rather than calling it the same join in another notation. A flattened vector and a three by two matrix have different shapes even when their entries appear in corresponding order.

Existing and new axes are different choices

Concatenate extends an existing axis; it does not create a new one to identify each input array. For the vector example, the two inputs become a longer vector. Their original boundary is not stored as a separate dimension in the result. If that boundary matters later, record the input lengths or choose an operation designed to introduce a new axis.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input sequence, every input shape and the selected axis. Then check that the other dimensions match and that the joined dimension has the expected combined length. These checks make the arrangement explicit without assigning extra meaning to the joined values.

NumPy rot90 turns an array through quarter turns within a specified plane

An array rotation changes where entries appear in a grid. NumPy rot90 performs quarter turns in a plane defined by two axes. Academia Master Trader explains this operation in English for readers in Monaco, using a small rectangular matrix. The examples distinguish rotation from sorting, numerical calculation and a simple row exchange. Following the corners makes the direction visible and helps explain why a rectangular array can change its shape.

Read the original matrix before turning it

After import numpy as np, define a = np.array([[1,2,3],[4,5,6]]). It has two rows and three columns. The top row is one, two, three, and the bottom row is four, five, six. Its four corners are one, three, four and six.

The call np.rot90(a) returns [[3,6],[2,5],[1,4]]. With the default settings, a two dimensional matrix turns counterclockwise by ninety degrees. Three becomes the top left entry, six becomes the top right entry and one becomes the bottom left entry. The result has three rows and two columns.

NumPy rot90

Count quarter turns with k

The parameter k is the number of quarter turns. The call np.rot90(a,k=2) returns [[6,5,4],[3,2,1]]. Two quarter turns give a half turn, returning the shape to two rows by three columns. Both the row order and the entry order within each row are reversed in this two dimensional example.

The call np.rot90(a,k=4) restores the original arrangement. Four quarter turns complete a full turn. These comparisons make k easier to interpret than a general phrase such as rotating repeatedly. The parameter counts ninety degree steps, not individual positions within a row or column.

A negative count turns in the opposite direction

The call np.rot90(a,k=-1) returns [[4,1],[5,2],[6,3]]. Under the default axis order, this is a clockwise quarter turn. Four moves to the top left corner and three moves to the bottom right corner. The output again has three rows and two columns.

A positive quarter turn and a negative quarter turn therefore have the same output shape but different arrangements. Shape alone does not establish direction. Trace a named corner from the input to the output, then check a second corner to confirm which way the matrix turned.

Axis order defines the orientation of the plane

The default axes are (0,1). The call np.rot90(a,k=1,axes=(1,0)) produces the same arrangement as np.rot90(a,k=-1,axes=(0,1)). Reversing the order of the two axes reverses the rotation direction for the same positive count.

The two axes must be different, and the input must have at least two dimensions. For an array with more than two dimensions, the axes specify the plane in which the turn occurs. Write both axes in order when describing such an operation. Naming only the two dimensions without their order leaves the direction unclear.

A rotated view is not necessarily an independent copy

NumPy describes the result as a rotated view. For a NumPy array, that means the output can refer to the original entries rather than storing an independent collection of values. If later work requires a separate array, request a copy explicitly, such as np.rot90(a).copy().

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, ordered axis pair and quarter turn count. Then trace the corners and check the resulting shape. A rotation rearranges the supplied entries; it does not generate additional measurements or make a numerical pattern more predictive.