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 full creates an array with a chosen shape and an explicit fill value

Creating an array and filling it with a known value can be one operation. NumPy full accepts the desired shape and a fill value, then returns a new array containing that value throughout the requested arrangement. The dimensions describe the positions available; the fill argument describes what those positions contain.

Academia Master Trader presents this explanation in English for readers in Malawi. The examples concern numerical array construction only. They do not represent prices, trading signals or financial results. The aim is to distinguish dimension lengths, stored values and data types before using a newly created array in a calculation.

Read shape and value separately

The expression np.full((2,3),7) creates rows [7,7,7] and [7,7,7]. The tuple (2,3) requests two rows and three columns. The separate argument seven is the value placed in each of those six positions.

The output shape is (2,3), not (7,). Seven does not request seven rows, and the shape tuple is not repeated as data inside the result. Writing the intended dimensions and the fill value on separate lines in an explanation helps keep these roles clear.

Original diagram: a two-by-three array has the value seven in all six positions, with the shape and fill value labelled separately.

Every entry in this example starts with the same value. That does not make the array a single scalar. It still has two dimensions and six distinct positions that can be addressed by their coordinates. Equal contents and equal structure are different questions.

One dimension is still an array

For a vector, the expression np.full(4,7) creates [7,7,7,7] with shape (4,). The first argument requests four positions along one axis. It does not create a four-by-four matrix, because no second dimension is specified.

A tuple containing one dimension length can express that same vector shape. In contrast, a shape of (1,4) requests a two-dimensional array with one row and four columns. The number of stored values may match, but the number of axes differs.

This distinction matters when another function expects a row, a column or a vector. A repeated number can make several outputs look similar in a short printout. Reading the shape explicitly avoids relying only on their visual resemblance.

The fill value influences the default data type

When dtype is omitted, the NumPy reference states that the default comes from the data type of an array made from the fill value. An integer fill and a floating-point fill can therefore lead to different output types even when the printed numbers appear similar.

For example, an integer seven and a floating-point seven express the same mathematical quantity, but they carry different type information. This lesson's basic example uses an integer fill. A program that needs a particular type should state that requirement with dtype rather than depending on appearance.

The expression np.full((2,3),7,dtype=float) requests floating-point entries in the same two-by-three arrangement. Changing the requested type does not change the row or column count. Shape, value and type are separate parts of the construction.

Conversion should match the intended meaning

An explicit data type asks NumPy to represent the supplied fill using that type. The chosen type should be able to represent the value the program intends to store. Do not treat dtype as a display setting that merely changes how an otherwise untouched value is printed.

This is particularly important when a fill includes a fractional part but the requested type is an integer type. If a later calculation needs that fraction, choosing a type that does not retain it changes the numerical contents before the calculation begins.

A clear explanation names both the fill value and the desired type. That makes the intended representation visible at the point of creation, rather than leaving a reader to infer it from values produced much later in the program.

An array-like fill follows a compatibility rule

Full also accepts an array-like fill value. The official reference gives the example of a two-by-two output filled from [1,2], producing rows [1,2] and [1,2]. The supplied pattern fits across the requested rows.

This does not mean that any sequence can fill any shape. The pattern must be compatible with the destination arrangement under NumPy's broadcasting rules. A short repeating description in ordinary language is not a substitute for checking how the dimensions align.

For an introductory example, a scalar fill makes the operation easiest to follow: one value goes into every position. When the fill itself has structure, describe its shape as well as the destination shape. That separates two different sources of dimensional information.

Storage order is not a different visible pattern

The order argument concerns how a multidimensional result is stored in memory. C-style and Fortran-style storage describe row-wise and column-wise memory organisation. They do not change the requested coordinate pattern into a different number of rows or columns.

The function returns a new array rather than filling a previously named array in place. If an existing variable receives the result, distinguish that assignment from an operation that changes the contents of some other array already stored elsewhere.

Make the starting state explicit

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. State the shape, fill value and intended type, then identify how many dimensions the output has. A known starting arrangement makes later changes easier to explain without confusing repeated values with the structure that holds them.

NumPy eye creates a two-dimensional array with ones on a chosen diagonal and zeros elsewhere

A diagonal pattern can be created directly from dimensions rather than extracted from an existing matrix. NumPy eye builds a two-dimensional array whose chosen diagonal contains ones and whose remaining positions contain zeros. The row count, column count and diagonal offset describe the structure before any values from an external dataset are involved.

Academia Master Trader presents this explanation in English for readers in Namibia. The examples concern numerical arrays and their arrangement only. They do not represent prices, trading signals or financial results. The aim is to understand what each size parameter controls and why a diagonal array need not always be square.

Begin with a square arrangement

The expression np.eye(3,dtype=int) creates rows [1,0,0], [0,1,0] and [0,0,1]. Its shape is (3,3). The first argument specifies three rows. Because the column count is omitted, it defaults to the same number, giving three columns as well.

The ones occupy the main diagonal. With zero-based indices, these are coordinates (0,0), (1,1) and (2,2). Every other coordinate contains zero. The integer data type in this example makes the printed values appear as integers rather than floating-point values.

Original diagram: a three-by-three array has ones at equal row and column indices, with zeros in every other position.

The function does not read those ones from another array. It creates the stated pattern. Nor does the number three become an entry repeated throughout the output: it sets a dimension length. Separating size arguments from array contents is the first step towards reading the expression correctly.

Rows and columns can have different lengths

The optional argument M specifies the number of columns. For example, np.eye(2,3,dtype=int) returns rows [1,0,0] and [0,1,0], with shape (2,3). The first number sets two rows; the second sets three columns.

This rectangle has two main-diagonal ones. There is no third row in which to place another one, even though a third column exists. The unused positions remain zero. The diagonal continues only as far as the available row and column positions permit.

Likewise, np.eye(3,2,dtype=int) produces rows [1,0], [0,1] and [0,0]. Its shape is (3,2). Swapping the two size arguments therefore changes the layout. Writing the expected shape next to an expression makes a row-count and column-count mix-up easier to notice.

Choose another diagonal with k

The parameter k selects the diagonal containing ones. Zero is the default and means the main diagonal. A positive value refers to a diagonal above it. The expression np.eye(3,k=1,dtype=int) produces rows [0,1,0], [0,0,1] and [0,0,0].

Here the ones occupy coordinates (0,1) and (1,2). The offset changes their positions, not their numeric value. It also does not add a column or row: the requested shape remains (3,3). The last row contains only zeros because the selected upper diagonal has no position in that row.

A negative offset selects a lower diagonal. With np.eye(3,k=-1,dtype=int), the rows are [0,0,0], [1,0,0] and [0,1,0]. The ones now occupy (1,0) and (2,1). The sign of k describes the diagonal's location, not negative entries in the resulting array.

A familiar special case has a precise boundary

The square arrangement with ones on the main diagonal and zeros elsewhere is the identity matrix. Eye can create that arrangement, but it can also create rectangles and shifted diagonal patterns. Calling every possible output an identity matrix would ignore those additional choices.

The shape and the offset should therefore accompany the name. A three-by-three main-diagonal result and a two-by-three result are both valid eye outputs, but they are not the same mathematical object. The function name alone does not settle the meaning of every array it can construct.

This also differs from constructing a diagonal matrix from a vector of supplied values. A function that places [2,5,8] on a diagonal preserves those supplied values. Eye instead uses ones for the selected diagonal. Decide which content the program needs before choosing the construction.

Data type and storage order are separate choices

The data-type parameter controls the type of the output entries. This lesson uses dtype=int so that the examples display zero and one as integers. Choosing a data type does not change which coordinates belong to the selected diagonal.

The order parameter concerns memory layout: C-style row-major storage or Fortran-style column-major storage. It does not mean that the diagonal moves from one side of the matrix to the other. The visible coordinate pattern is described by the dimensions and k, independently of that storage-order choice.

For introductory work, keep these questions separate: what shape is required, which diagonal contains ones and which data type suits the later calculation? Further options should be considered only when the program needs them. Adding parameters without explaining their role can obscure a simple construction.

Explain the structure before using it

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. State the row count, column count and diagonal offset, then identify one position that contains one and another that contains zero. This turns a compact array expression into a clear description of the intended structure.

NumPy tril preserves the lower region of an array while keeping its original shape

A lower triangular arrangement can be represented inside an ordinary rectangular array. NumPy tril creates that arrangement by keeping entries on or below a chosen diagonal and replacing entries above it with zeros. The output retains the input shape, so the operation changes selected values rather than cutting away part of the array.

Academia Master Trader presents this explanation in English for readers in Botswana. The examples describe array positions and numerical structure only. They do not represent prices, trading signals or financial results. Understanding the boundary diagonal helps distinguish a lower-region arrangement from a smaller array, a sorted sequence or a collection of minimum values.

Follow the default boundary

Let x have rows [1,2,3], [4,5,6] and [7,8,9]. Its shape is (3,3). The expression np.tril(x) returns rows [1,0,0], [4,5,0] and [7,8,9]. The output is still a three-by-three array.

One, five and nine lie on the main diagonal and remain in place. Four, seven and eight lie below it and also remain. Two, three and six lie above it, so their output positions contain zeros. None of the retained values moves to a new coordinate.

Original diagram: the lower region of a three-by-three matrix remains while the entries above the main diagonal become zeros.

The zeros are part of the resulting data structure. They are not missing cells or an instruction to ignore those coordinates. If a later calculation adds, averages or otherwise processes the full array, those zeros participate according to that later operation's rules.

Selection depends on position

With zero-based indices, the main diagonal has equal row and column indices. Below it, the row index is greater than the column index. The default tril operation therefore keeps positions whose column index is no greater than their row index.

The value at (2,0) remains because it lies below the main diagonal. The value at (0,2) becomes zero because it lies above it. This decision would be the same if the original values were negative, repeated or much larger than the example numbers.

Lower means a region of the array, not a ranking by numerical size. A very small number above the diagonal is still replaced. A very large number below the diagonal is still retained. The function does not compare each value with its neighbours or rearrange the rows to create a sorted order.

A negative offset excludes the main diagonal

The parameter k determines the boundary. Zero is the default and includes the main diagonal. A negative k moves the boundary below it. For x, np.tril(x,k=-1) returns rows [0,0,0], [4,0,0] and [7,8,0].

This is the strictly lower region for the square example. The main diagonal itself has become zero, while the first diagonal below it remains. Moving the boundary farther down would keep fewer positions. The parameter changes which entries survive, not where the entries are placed.

A positive offset moves the boundary above the main diagonal. The expression np.tril(x,k=1) returns rows [1,2,0], [4,5,6] and [7,8,9]. Two and six now remain because they lie on the selected upper diagonal. Three remains above that boundary and is replaced with zero.

Rectangles use the same coordinate rule

Consider a four-by-three array with rows [1,2,3], [4,5,6], [7,8,9] and [10,11,12]. The operation np.tril(x,k=-1) for this rectangular x gives rows [0,0,0], [4,0,0], [7,8,0] and [10,11,12].

Every entry in the last row is below the main diagonal, so that row remains unchanged under this boundary. The result still has shape (4,3). It does not become a square matrix simply because the operation is described using a triangle.

A rectangular example makes the index rule particularly useful. The visible outline of retained entries depends on the available number of rows and columns. The function follows positions relative to the chosen diagonal rather than resizing the array to match a drawing.

Higher dimensions use the final two axes

For an array with more than two dimensions, tril applies to the final two axes. The earlier axes identify the surrounding collections of matrix-like planes. Each of those planes receives the lower-region rule in its own row and column positions.

Before interpreting such an output, write down the full shape and identify which dimensions are last. A program that treats the first two axes as the relevant plane may attach the wrong meaning to the result even when the array itself is valid.

The NumPy reference describes the output as having the same shape and data type as the input, and as a copy. Keep that result separate from an assumption that the original input has been edited directly. Naming the output makes the data flow easier to follow.

Keep the operation distinct from later arithmetic

Tril does not return only the retained entries as a compact vector. It does not add them, count them or infer why the lower region matters. Those tasks require their own operations and an explanation of the array's meaning.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Record the input shape, identify the chosen diagonal and describe which positions become zero. That account makes the lower-region rule clear without confusing it with sorting, extraction or a change in the number of dimensions.

NumPy triu keeps the upper part of an array and replaces entries below a diagonal with zeros

Keeping the upper part of a matrix does not require removing its lower rows or changing its rectangular shape. NumPy triu returns a copy in which entries below a selected diagonal are replaced with zeros. The remaining positions keep their original values. The name describes a position rule, not a search for large numbers.

Academia Master Trader presents this explanation in English for readers in Zimbabwe. The examples concern array organisation only. They do not represent prices, trading signals or financial results. The aim is to understand the boundary defined by a diagonal and to distinguish zeroing selected positions from extracting a smaller collection of entries.

Start with the main diagonal

Let x have rows [1,2,3], [4,5,6] and [7,8,9], giving it shape (3,3). The expression np.triu(x) produces rows [1,2,3], [0,5,6] and [0,0,9]. The output still has three rows and three columns.

The default diagonal is the main diagonal. Values one, five and nine remain on that boundary. Values two, three and six remain above it. The positions originally holding four, seven and eight are below the boundary, so the output holds zeros in those positions instead.

Original diagram: a three-by-three matrix keeps its main diagonal and values above it while the lower three entries become zeros.

The zeros are actual values in the output array, not blank spaces. They do not indicate that NumPy failed to obtain an observation. They result from the chosen structural operation. If the entries carry a real-world meaning, that meaning must be considered separately from the matrix layout.

Describe the boundary with indices

Using zero-based indices, the main diagonal contains positions where the row and column indices are equal. Above that diagonal, the column index is greater than the row index. Below it, the row index is greater than the column index.

For the default operation, triu retains positions where the column index is at least the row index. It zeros the positions that do not satisfy that relationship. This describes why the value four at coordinate (1,0) is replaced, while six at (1,2) remains.

The comparison concerns indices, not the size or sign of each entry. A negative value above the selected diagonal remains negative. A large positive value below it becomes zero. Reordering the numeric values without changing their positions does not change which locations belong to the upper region.

Shift the diagonal with k

The parameter k chooses the boundary diagonal. Its default is zero. A positive value moves the boundary above the main diagonal. For the same x, np.triu(x,k=1) returns rows [0,2,3], [0,0,6] and [0,0,0].

That result keeps the entries strictly above the main diagonal and zeros the main diagonal itself along with the region below it. The original values are not shifted into neighbouring cells. The boundary changes, while each surviving value stays at its existing coordinate.

A negative k moves the boundary below the main diagonal. The expression np.triu(x,k=-1) gives rows [1,2,3], [4,5,6] and [0,8,9]. In this case, only seven is below the selected boundary. Including one lower diagonal retains more entries than the default operation.

A rectangular array still has a diagonal rule

The input need not be square. Consider rows [1,2,3], [4,5,6], [7,8,9] and [10,11,12]. This array has shape (4,3). With k equal to minus one, the result has rows [1,2,3], [4,5,6], [0,8,9] and [0,0,12].

This example follows the same coordinate rule even though the array has more rows than columns. The last value twelve sits on the first diagonal below the main diagonal, so it remains. Ten and eleven lie farther below the selected boundary and become zero.

A rectangular outline does not prevent the operation from defining an upper region. It simply changes how many positions each row has on either side of the boundary. Describing the coordinates is more precise than expecting every output to look like a geometrically complete triangle.

Do not confuse zeroing with extraction

The result of triu remains an arranged array with the original matrix shape. It is not a compact vector containing only retained entries. Nor does it add those entries together. A later operation may extract positions or calculate a sum, but those are separate steps.

The official reference describes triu as returning a copy. This is different from a description that promises to edit the original input directly. Keep the output in a named variable when the program needs to use the upper-region arrangement in subsequent work.

For arrays with more than two dimensions, NumPy applies triu to the final two axes. The earlier axes identify the surrounding collections. Before interpreting a multidimensional result, identify which two dimensions form those matrix-like planes rather than assuming that the first two axes define the operation.

Connect the rule to the intended structure

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Name the shape, identify the boundary diagonal and follow one retained position and one zeroed position. This keeps the geometric rule distinct from numerical ranking, data selection and later calculations.

NumPy diag extracts a matrix diagonal or builds a diagonal matrix from a vector

The same NumPy function can perform two different structural operations depending on the number of dimensions in its input. With a matrix, diag extracts entries along a chosen diagonal. With a vector, it constructs a two-dimensional array and places the supplied values on a chosen diagonal. Recognising that difference comes before interpreting the output.

Academia Master Trader presents this explanation in English for readers in Zambia. The examples describe numerical arrays and positions only. They do not represent prices, trading signals or financial results. The aim is to follow which entries are selected, which positions are filled and how the output shape relates to the input.

Extract the main diagonal from a matrix

Consider a matrix x with rows [1,2,3], [4,5,6] and [7,8,9]. Its shape is (3,3). The expression np.diag(x) returns the vector [1,5,9], whose shape is (3,). These entries occupy the main diagonal, from the upper-left position towards the lower-right position.

The main diagonal contains positions where the row index equals the column index. Using zero-based indices, the selected coordinates are (0,0), (1,1) and (2,2). The function follows that coordinate relationship. It does not select the smallest value in each row or search for a numerical pattern among the entries.

Original diagram: the main diagonal one five nine is selected from a three-by-three matrix and returned as a vector.

The result is a vector rather than a matrix with empty off-diagonal positions. This distinction matters when another operation expects a two-dimensional input. A list of diagonal values and a diagonal matrix are different structures, even when they contain the same selected numbers.

Move to a neighbouring diagonal

The parameter k selects the diagonal. Its default value is zero, which means the main diagonal. A positive value refers to a diagonal above the main diagonal. For the same x, np.diag(x,k=1) returns [2,6], selecting coordinates (0,1) and (1,2).

A negative value refers to a diagonal below the main diagonal. The expression np.diag(x,k=-1) returns [4,8], from coordinates (1,0) and (2,1). Both neighbouring diagonals are shorter than the main diagonal in this square example because they start away from a corner.

The offset is a position rule, not an amount added to each selected value. Moving from k equal to zero to k equal to one changes which entries are extracted. It does not transform [1,5,9] into [2,6,10]. The output length follows the available positions on the chosen diagonal.

A vector changes the operation

Now let v be the one-dimensional array [2,5,8]. The expression np.diag(v) constructs a matrix with rows [2,0,0], [0,5,0] and [0,0,8]. The values from v occupy the main diagonal, and the remaining entries are zero.

The shape changes from (3,) to (3,3). Unlike extraction, this operation creates the surrounding two-dimensional arrangement. The zero values are part of the output. They are not missing observations, blank cells or values recovered from some earlier matrix.

For a vector input, an offset moves the supplied values to a different diagonal of the constructed array. The example np.diag([2,5,8],k=1) produces a four-by-four array with two, five and eight immediately above the main diagonal. The extra dimension length provides room for that offset.

Extraction followed by construction is not restoration

Apply diag to the matrix x, then apply diag again to the resulting vector. The first call gives [1,5,9]. The second constructs rows [1,0,0], [0,5,0] and [0,0,9]. This is not the original x, because the off-diagonal entries from x were not retained in the extracted vector.

The two calls therefore do not undo each other in the general case. One selects a subset of entries; the other builds a matrix with zeros elsewhere. Matching the original shape after the second call does not recover the information absent from the intermediate result.

That distinction is useful whenever code switches between a compact collection of selected values and a larger arranged structure. Record the meaning of the intermediate array rather than judging the process only by the final number of rows and columns.

Keep extraction separate from addition

Extracting a diagonal leaves its entries as separate elements. For x, the result [1,5,9] is different from the scalar fifteen obtained by adding those three numbers. NumPy also documents trace as a separate operation for summing along diagonals.

A later calculation may deliberately use the extracted vector, but diag itself should not be described as performing that calculation. State whether the program needs positions, a vector of values, a diagonal matrix or a sum. Those outputs answer different questions.

Check storage assumptions before changing values

The official diag reference directs readers to the more detailed diagonal documentation when they plan to write to an extracted result, because copy and view behaviour depends on the NumPy version. An introductory example should not promise that changing the extracted array always changes the original matrix, or that it never does.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify whether the input is a vector or a matrix, name the offset and describe the resulting shape. These steps keep diagonal selection distinct from matrix construction and from any arithmetic performed afterwards.

NumPy rot90 turns an array through quarter rotations in a plane defined by two axes

A rectangular array can be turned without changing the numbers it contains. After a quarter rotation, however, a row can become a column and the lengths of those two dimensions can exchange places. NumPy rot90 describes this operation with a count of quarter turns and an ordered pair of axes.

Academia Master Trader presents this explanation in English for readers in Tanzania. The examples concern the arrangement of numerical data, not prices, trading signals or financial results. Understanding the position changes first makes it easier to distinguish a rotation from a transpose, a reversal or a cyclic shift.

Start with a rectangle rather than a square

Let x be a two-dimensional array with rows [1,2,3] and [4,5,6]. Its shape is (2,3): two rows and three columns. The expression np.rot90(x) returns an array with rows [3,6], [2,5] and [1,4]. Its shape is (3,2).

The default operation turns the array through ninety degrees counterclockwise in the plane of axes zero and one. The original upper-right value, three, becomes the upper-left value. Six becomes the upper-right value. Following a distinctive corner is a useful way to understand the direction without relying only on the outline of the rectangle.

Original diagram: rows one two three and four five six rotate counterclockwise into rows three six, two five and one four.

The six values are all still present, but their coordinates have changed. The shape changes because a quarter turn exchanges the two side lengths of this non-square rectangle. Using a square example alone could hide that consequence, since exchanging equal lengths leaves the shape looking the same.

The parameter counts quarter turns

The parameter k specifies how many ninety-degree rotations to apply. The default is one. For the same rectangle, np.rot90(x,2) gives rows [6,5,4] and [3,2,1]. That is a half turn, and its shape returns to (2,3).

With k equal to three, the result has rows [4,1], [5,2] and [6,3], with shape (3,2). Four quarter turns return the original arrangement. A zero count also leaves the arrangement unchanged. These outcomes describe position changes; they do not add ninety, two or four to the array values.

A negative count reverses the turn direction. With the default axes, np.rot90(x,-1) makes one clockwise quarter turn and gives the same arrangement as three counterclockwise quarter turns. Writing the direction alongside the expression helps a reader connect the number to the intended geometry.

The order of the axes matters

Rot90 takes an ordered pair of different axes. The rotation direction is from the first axis towards the second. For a two-dimensional array with the default axes (0,1) and k equal to one, the familiar visual result is counterclockwise.

Changing the pair to (1,0) reverses that direction for the same positive count. Thus np.rot90(x,1,axes=(1,0)) is equivalent in arrangement to np.rot90(x,-1,axes=(0,1)). The pair is not merely an unordered list of dimensions that happen to participate.

The two axes must be different, and the input needs at least two dimensions. A vector has only one axis, so the operation requires a plane that the vector alone does not provide. If a sequence is meant to represent a row or column within a plane, that shape should be made explicit before describing a rotation.

Distinguish a turn from a transpose

For the rectangle in this lesson, the transpose has rows [1,4], [2,5] and [3,6]. The default quarter rotation instead has rows [3,6], [2,5] and [1,4]. Both shapes are (3,2), but the arrays are not arranged the same way.

A shape comparison therefore cannot establish which transformation occurred. Transposition exchanges the two axes without the same direction reversal that appears in a quarter rotation. Comparing the positions of one, three, four and six makes the difference visible immediately.

Nor is a rotation the same as rolling values along a sequence. A cyclic shift returns entries that pass an end to the opposite end of a chosen dimension. A quarter rotation changes how positions relate across a plane. Their names should describe the operation actually intended by the program.

Higher dimensions still need a chosen plane

An array with more than two dimensions has several possible pairs of axes. Rot90 can act in the plane named by one such pair. The remaining dimensions are not replaced with new axes; the selected plane determines how the existing entries are rearranged.

Before interpreting the result, label what each dimension means. If an array has separate dimensions for several collections, row positions and column positions, the axes selected for rotation should match the intended plane. A visual description based on a two-dimensional page is only a guide when the actual array has more dimensions.

The official NumPy reference describes the result as a rotated view. Code should not assume that the operation provides independent storage for every value. When a separate array is required for later changes, make that intention explicit rather than inferring it from the new orientation.

Describe coordinates as well as appearance

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Record the starting shape, the ordered axes and the quarter-turn count, then follow a corner value to its new position. That short explanation keeps the direction, the geometry and the numerical contents separate.

NumPy roll shifts array positions cyclically and brings displaced values back at the opposite end

Moving a sequence by one position can mean several different things. A program might discard a value, leave an empty position or bring the value back at the other end. NumPy roll uses the third rule. It shifts positions cyclically, so entries that pass beyond an end reappear at the opposite end rather than disappearing.

Academia Master Trader presents this explanation in English for readers in Uganda. The examples describe numerical array organisation only. They do not represent prices, trading signals or financial results. The aim is to understand where values move, how the chosen axis affects that movement and why a cyclic shift needs a clear interpretation.

One positive shift in a vector

Consider the vector [2,5,8,11]. The expression np.roll([2,5,8,11],1) produces [11,2,5,8]. Each value moves one position towards the end. The value eleven passes beyond the last position and returns at the first. The output still contains four values and has shape (4,).

The shift is a count of positions, not an amount added to the numbers. Two becomes the second entry; it does not become three. Likewise, the eleven at the beginning is the original last entry, not a new observation or a value calculated from the other three.

Original diagram: a positive shift of one moves eleven from the last position to the first while the remaining values move one place.

A negative shift changes the direction. The expression np.roll([2,5,8,11],-1) produces [5,8,11,2]. The first value moves beyond the beginning and returns at the end. Both directions preserve the input shape and the values present in the sequence.

Count positions around the cycle

A shift equal to the length of this four-element vector brings every value back to its starting position. A shift of four therefore produces [2,5,8,11] again. A shift of five has the same visible result as a shift of one because it includes one complete turn plus one extra position.

This relationship follows from the cyclic rule. It does not mean the operation sorts, groups or simplifies the values. The original order is preserved around the cycle, but the position chosen as the beginning changes. Repeated values can make that change harder to see, so distinct example numbers are useful when explaining the mapping.

Choose the direction within a matrix

Let x have rows [1,2,3] and [4,5,6], giving it shape (2,3). The expression np.roll(x,1,axis=0) produces rows [4,5,6] and [1,2,3]. The rows shift along the first axis. With only two rows, one positive step exchanges their positions.

For np.roll(x,1,axis=1), the rows become [3,1,2] and [6,4,5]. Each row is shifted along its columns. The last entry of each row returns at the beginning of that same row. Values do not move between rows in this axis-one example.

The output shape remains (2,3) for both choices. Axis specifies the dimension in which positions change. It does not select a particular numeric value and does not add a dimension to the result. Naming the direction in words makes the intended operation easier to review.

Without an axis, flattening comes first

The default behaviour is different from choosing axis zero. When axis is omitted, roll flattens the input before shifting and then restores the original shape. For the same matrix, np.roll(x,1) produces rows [6,1,2] and [3,4,5].

The flattened order starts as [1,2,3,4,5,6]. After a shift of one it is [6,1,2,3,4,5]. Restoring the two-by-three shape explains the resulting rows. In this case, a value can cross the boundary between rows because the shift took place in the flattened sequence.

The final matrix still has shape (2,3). Shape preservation does not mean that the default operation treats each row separately. The intermediate order matters. An explicit axis is useful when the program must keep the shift within a particular dimension.

Several axes can move together

Roll also accepts tuples for shift and axis. When both are tuples, the corresponding entries describe the shift for each selected axis. A single integer shift with a tuple of axes applies that same shift to all the listed axes. The mapping between these arguments should be written clearly when more than one direction is involved.

For an introductory explanation, it is often clearer to understand one axis at a time before combining them. Follow one distinctive value from its original coordinates to its final coordinates. That position-based description avoids confusing a cyclic shift with a reversal of the entire order.

A cyclic arrangement needs a reason

Bringing the last value back to the beginning is a structural rule, not proof that the underlying observations form a natural cycle. If positions represent a particular sequence, the program should explain why wrapping the end to the start is appropriate. Roll does not determine that meaning on its own.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the shape, the direction and the number of positions, then follow the entries that cross an end. This keeps cyclic movement distinct from addition, reversal and the creation of new data.

NumPy flip reverses the order along chosen axes while keeping the array shape unchanged

Changing the direction in which an array is read is different from sorting its values or exchanging its dimensions. NumPy flip reverses the order of entries along selected axes. The values move to different positions in that arrangement, but the shape of the array stays the same. Understanding which axis is reversed explains the result more clearly than the word flip alone.

Academia Master Trader presents this explanation in English for readers in Kenya. The examples concern numerical array structure only. They do not represent prices, trading signals or financial results. The aim is to separate the order of positions from the meaning of the numbers stored at those positions.

Reverse a single sequence

For the vector [2,5,8], the expression np.flip([2,5,8]) produces [8,5,2]. The last position is read first, the middle position remains in the middle and the first position is read last. Both the original vector and the result have shape (3,).

This is not an instruction to sort numbers from largest to smallest. The example happens to begin with increasing values, so its reverse looks like descending order. With [5,2,8], reversing gives [8,2,5], which is not descending order. Flip follows the original positions, not a ranking rule based on value.

A matrix has more than one direction

Let x be a matrix with rows [1,2,3] and [4,5,6]. Its shape is (2,3). The expression np.flip(x,axis=0) produces rows [4,5,6] and [1,2,3]. The two rows exchange their order, while the order of entries within each row remains unchanged.

The result still has two rows and three columns. Axis zero identifies the dimension whose positions are being reversed. It does not mean that the first value becomes zero or that a row is removed. The numeric axis label describes an organisational direction within the array.

Original diagram: reversing axis zero exchanges the two rows of a matrix and preserves shape two by three.

With np.flip(x,axis=1), the result instead has rows [3,2,1] and [6,5,4]. The order of columns is reversed within each row. The first row remains the first row. Shape (2,3) is preserved here too, even though different positions have changed compared with the axis-zero example.

The default reverses every axis

Calling np.flip(x) without an axis reverses all axes of the input. For the example matrix, the result has rows [6,5,4] and [3,2,1]. Both the row order and the column order have been reversed. This differs from reversing only one of the two axes.

It is therefore important not to read an omitted axis as an automatic choice of axis zero. The documented default is None, which selects all axes. An explicit axis can make the intention clearer when a program should reverse only one direction of a multidimensional array.

A tuple can also identify several axes. In a two-dimensional matrix, np.flip(x,axis=(0,1)) reverses both available axes. For arrays with more dimensions, a tuple can select a subset rather than all of them. Each selected axis is reversed without changing its length.

Reversal is not transposition

A transpose changes the positions of axes. A flip changes the direction of positions along an axis. In the example, every flip result remains shape (2,3). Transposing the original matrix would give shape (3,2). These operations should not be treated as interchangeable ways to change a matrix's appearance.

The distinction is easier to see with a rectangular matrix than with a square one. A square matrix can keep the same shape after transposition, even though its positions have been rearranged differently. Shape is useful evidence, but the actual mapping of positions is also needed to explain the operation.

A view is not an independent copy

For a NumPy array, flip returns a view with the selected axis directions reversed. A view can share the original data rather than storing a separate, independent set of values. A different displayed order does not by itself prove that new independent storage has been created.

This matters if the program later writes through that view. A change to shared data can also be visible through the original array. If independent storage is required, that intention should be expressed separately with an appropriate copy. Reading the reversed arrangement and changing its underlying data are different activities.

Keep the meaning of the order clear

Reversing observations does not create new observations or alter the source from which the values came. It changes their order in the array view. If positions represent a particular sequence, the program should document why reversing that sequence is appropriate before using it in a later calculation.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the input shape, name the axes being reversed and follow the resulting positions. This keeps reversal separate from sorting, transposition and copying.

NumPy stack joins equally shaped arrays along a new axis rather than extending an old one

Two arrays can contain matching sets of positions without belonging in one long sequence. Sometimes the useful result keeps each input together and adds a dimension that identifies which input supplied a value. NumPy stack performs that kind of join. It combines arrays along a new axis instead of extending an axis that already exists.

Academia Master Trader presents this explanation in English for readers in Ghana. The examples concern the structure of numerical arrays only. They do not represent market prices, trading signals or financial results. The aim is to make the relationship between input shapes, the new axis and the final arrangement easy to follow.

Two vectors become a matrix

Let a be the vector [1,2,3] and b the vector [4,5,6]. Each input has shape (3,). The expression np.stack((a,b),axis=0) produces a matrix whose rows are [1,2,3] and [4,5,6]. Its shape is (2,3).

The new first axis has length two because there are two input arrays. The original axis of length three remains present as the second axis. Each input was one-dimensional, and the result is two-dimensional. There are six elements in total, but the extra dimension is the main structural change.

Original diagram: stack joins two vectors of three values into a matrix with two rows and three columns.

The values are neither added nor averaged. The first row comes from a and the second from b because the inputs were supplied in that order. Reversing the sequence to (b,a) changes their order along the new axis. Stack does not select an order based on the values themselves.

Put the new axis last

With the same vectors, np.stack((a,b),axis=-1) produces the rows [1,4], [2,5] and [3,6]. The output shape is (3,2). The new axis now comes last, so each row brings together values from the same original position in the two inputs.

This arrangement still contains six elements. However, shape (3,2) is different from shape (2,3). One result has three rows and two columns; the other has two rows and three columns. Counting elements alone cannot tell a reader how the axes have been arranged.

For this two-dimensional result, axis one and axis minus one identify the same final axis. A negative axis index counts from the end of the result. It is helpful to describe the intended dimensions in words before choosing the numeric index, especially when the inputs have more than one dimension.

Every input must have the same shape

Stack requires the input arrays to have the same shape. A vector with shape (3,) does not match a matrix with shape (1,3), even though both contain three values. Their numbers of dimensions differ. The visible values alone do not establish compatibility.

Likewise, two vectors of lengths three and four do not meet the requirement. Stack does not invent a fourth value for the shorter vector. Any decision to pad, remove or otherwise reorganise values belongs to an earlier preparation step and needs a reason that comes from the data's intended use.

Shape equality is a structural condition, not proof of matching meaning. Two arrays may have the same shape while containing different units or referring to different periods. The function has no knowledge of those distinctions. Anyone preparing the inputs must decide whether corresponding positions should be grouped together.

Stacking matrices adds a third dimension

Suppose two inputs both have shape (2,3). Stacking them with axis zero produces shape (2,2,3). The first two in that shape records the number of inputs. The next two and the final three come from the two rows and three columns within each input.

Putting the new axis last instead produces shape (2,3,2). The new dimension still has length two, but its position in the shape changes. This is why axis is an instruction about where to insert a dimension, not merely a choice between placing items visually above or beside one another.

A useful check is to mark the new dimension separately when writing the expected shape. Then read the remaining dimensions in their original order. The number of dimensions should increase by one compared with each input, while the new dimension's length should equal the number of arrays supplied.

Contrast stack with concatenate

Concatenate joins along an existing axis. For the vectors [1,2,3] and [4,5,6], concatenation along axis zero produces [1,2,3,4,5,6], with shape (6,). Stack with axis zero instead produces shape (2,3). The two functions preserve the same example values but organise them differently.

The choice therefore starts with the intended structure. If the inputs should become sections of one existing dimension, concatenation may express that intention. If an additional dimension should identify the separate inputs, stack expresses a different relationship. Neither function decides what the added organisation means in the subject being studied.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to the educational material. Write down each input shape, identify where the new axis belongs and compare the output with that description. This keeps values, positions and dimensions separate throughout the join.

NumPy concatenate junta arrays ao longo de um eixo existente sem somar os seus valores

Juntar duas estruturas numéricas não significa somar os números que ocupam posições semelhantes. A função concatenate do NumPy reúne uma sequência de arrays ao longo de um eixo que já existe. A ordem das entradas, a escolha do eixo e a compatibilidade das formas determinam como os valores aparecem na saída.

A Academia Master Trader apresenta esta explicação em português para leitores de Timor-Leste. Os exemplos descrevem a organização de dados, sem representar cotações, sinais de negociação ou resultados financeiros. A proposta é acompanhar uma junção simples e distinguir o crescimento de uma dimensão da criação de um eixo novo.

Juntar duas matrizes pelas linhas

Considere a matriz a com as linhas [1,2] e [3,4], cuja forma é (2,2). Considere também a matriz b com uma única linha [5,6], cuja forma é (1,2). Ambas têm duas colunas, embora possuam quantidades diferentes de linhas.

A expressão np.concatenate((a,b),axis=0) produz três linhas: [1,2], [3,4] e [5,6]. A forma final é (3,2). O primeiro eixo aumentou de duas mais uma para três posições, enquanto o segundo permaneceu com duas posições. Os valores não foram somados nem ordenados por tamanho.

Figura própria: duas linhas da matriz a e uma linha da matriz b formam uma matriz com três linhas e duas colunas.

A sequência (a,b) indica quais arrays serão reunidos e em que ordem. O conteúdo de a aparece antes do conteúdo de b ao longo do eixo escolhido. Se a sequência das entradas mudar, a organização da saída também poderá mudar. A função não procura automaticamente uma ordem cronológica ou uma correspondência por nomes.

Compatibilidade fora do eixo escolhido

As formas podem ser diferentes na dimensão que recebe a junção. Nas restantes dimensões, têm de ser compatíveis pela igualdade dos tamanhos. No exemplo, o número de linhas pode variar porque a junção ocorre no eixo zero. As duas colunas precisam de corresponder em quantidade.

Uma matriz com duas colunas não pode ser simplesmente concatenada pelas linhas com outra que tenha três colunas. É necessário esclarecer primeiro qual é a estrutura pretendida. A função não preenche automaticamente uma coluna em falta nem decide quais valores deveriam ser acrescentados. A compatibilidade faz parte da preparação dos dados.

Também convém separar a forma do significado. Duas tabelas podem ter a mesma quantidade de colunas e ainda assim representar campos diferentes. A função trabalha com posições numéricas. Cabe a quem organiza os dados garantir que as colunas reunidas têm a interpretação adequada ao uso posterior.

Juntar pelas colunas

Para juntar ao longo do eixo um, a quantidade de linhas deve coincidir. Retome a matriz a de forma (2,2) e considere uma matriz c com as linhas [5] e [6], de forma (2,1). A expressão np.concatenate((a,c),axis=1) produz as linhas [1,2,5] e [3,4,6].

A forma final é (2,3). O número de linhas mantém-se em dois, enquanto as duas colunas de a se juntam à coluna de c. O resultado tem seis elementos, tal como o exemplo de três linhas por duas colunas. A igualdade na contagem total não torna as duas formas equivalentes.

Antes da operação, escreva a forma de cada entrada e identifique a dimensão que vai crescer. Depois confirme que as restantes dimensões são iguais. Esta sequência de leitura é mais clara do que tentar deduzir o eixo apenas a partir da forma visual da matriz impressa.

Um eixo existente não é um eixo novo

Concatenate prolonga um eixo existente. Não cria por si só uma dimensão adicional para guardar cada entrada numa camada separada. A função stack tem essa outra finalidade, ao reunir arrays ao longo de um eixo novo. As duas operações respondem a perguntas diferentes sobre a organização pretendida.

Para dois vetores [1,2] e [3,4], concatenar ao longo do eixo zero produz o vetor [1,2,3,4], de forma (4,). Não produz automaticamente duas linhas de dois valores. A intenção de criar uma matriz precisa de ser expressa pela operação apropriada, não inferida da presença de duas entradas.

Achatar antes de juntar

Quando axis recebe None, concatenate achata as entradas antes da junção. Para as matrizes a e b do primeiro exemplo, np.concatenate((a,b),axis=None) produz [1,2,3,4,5,6]. A saída é unidimensional e tem forma (6,).

Esta opção altera a organização das dimensões que se vê no resultado. Os valores continuam presentes, mas já não estão distribuídos pelas três linhas da primeira junção. Por isso, convém escolher conscientemente entre conservar os eixos e reunir todos os elementos numa sequência única.

Juntar estruturas não valida a origem

A função não determina se as entradas foram recolhidas no mesmo período ou se possuem unidades equivalentes. Uma junção tecnicamente possível pode exigir revisão do contexto. Registar a origem e a ordem das entradas permite interpretar o array final sem atribuir à função verificações que ela não realiza.

Continue a aprender com a Academia Master Trader em academiamastertrader.com.br. Aprenda dá acesso aos conteúdos educativos. Identifique as formas, escolha o eixo e acompanhe a ordem das entradas. Assim, cada posição da saída pode ser relacionada com a estrutura de onde veio, sem confundir junção, soma e criação de dimensões.