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 repeat expands entries by their repetition counts rather than multiplying values

Repeating an entry changes how many times it appears. It does not multiply the numerical value stored there. NumPy repeat makes that distinction explicit: the repeats argument sets the number of appearances, while axis identifies the direction in which the array expands. When axis is omitted, the input is flattened and the result is one-dimensional.

Academia Master Trader presents this lesson for English-language study in Antigua and Barbuda. The numbers are invented teaching values, not prices, transaction counts or financial results. Short examples show how repetition changes the arrangement and size of an array, while leaving the repeated values themselves unchanged.

Read a uniform repetition count

Let x be [4,7,10]. The expression np.repeat(x,2) produces [4,4,7,7,10,10]. Each original entry appears twice, next to itself. The input has three positions, while the output has six. The value 4 remains 4 in both of its output positions; it does not become 8.

The count two means two total appearances for each entry, not the original appearance plus two additional copies. This detail is worth stating before drawing the result. If the count is three, each entry appears three times. The repeats argument describes the total number of repetitions in the output.

Original diagram showing each entry of a three-element array appearing twice with NumPy repeat

Keep each repeated group together

The sequence [4,4,7,7,10,10] contains a group for each original entry in its original order. It is not the sequence [4,7,10,4,7,10]. Repeating individual entries and repeating the whole input as a block describe different arrangements, even though both examples contain six values.

This distinction makes a handwritten output easier to check. Start at the first input position, write it the requested number of times, then move to the next input position. Do not return to the beginning of the input after writing only one appearance of each value.

Give different entries different counts

The repeats argument can also supply a count for each position. For x=[4,7,10], np.repeat(x,[1,3,2]) produces [4,7,7,7,10,10]. The first entry appears once, the second three times and the third twice. The output length is six because those counts sum to six.

The counts belong to positions, not to unique numerical values. If two input positions happen to contain the same number, each position still has its own repetition count. Keeping a small table of input positions and counts avoids treating repeat as a rule for all occurrences of a particular number.

Specify axis 1 to expand columns

Let a contain rows [2,5] and [8,11], with shape (2,2). The expression np.repeat(a,2,axis=1) gives rows [2,2,5,5] and [8,8,11,11]. Axis 1 is the column axis, so its length expands from two to four while the number of rows stays two.

You can also read this as repeating complete columns. The first input column, containing 2 and 8, appears twice. The second, containing 5 and 11, appears twice. The column groups remain in their original order. Naming the output shape (2,4) makes the structural change clear.

Specify axis 0 to expand rows

For the same input, np.repeat(a,2,axis=0) gives rows [2,5], [2,5], [8,11] and [8,11]. Complete rows are repeated. The output shape is (4,2): four rows and two columns. This is different from repeating the entries inside each row along axis 1.

With different counts, np.repeat(a,[1,2],axis=0) gives rows [2,5], [8,11] and [8,11]. The first row appears once and the second twice. Its shape is (3,2). The order of the counts follows the order of positions along the selected axis.

Recognise the flattened default

The default axis is None. The documentation says repeat uses the flattened input and returns a flat output. For the same two-dimensional input, np.repeat(a,2) produces the one-dimensional sequence [2,2,5,5,8,8,11,11]. Its shape is (8,), not (2,4) or (4,2).

All three calls produce eight values when every entry is repeated twice, but their shapes and arrangements differ. A count of values is therefore not enough to describe the result. Include axis and output shape whenever you explain repetition on a matrix.

Keep count alignment explicit

The documentation states that the repetition counts are broadcast to fit the selected axis. A single count can apply uniformly, as in the examples with repeats=2. A list of counts can assign different repetitions to positions, as in the example with two row counts.

Before using position-specific counts, identify the length of the selected axis and how the counts align with it. For the simple row example, two counts describe two input rows. This makes the relationship visible without assuming that any arbitrary count list will match any input shape.

Separate repeated entries from new observations

If an array represents recorded observations, repeating its entries does not create additional independently observed information. It creates additional positions containing selected existing values. The output can be useful as an arrangement, but the meaning of a repetition should be stated separately from its numerical appearance.

The same care applies to labels. If rows or columns carry names, an expanded presentation needs labels that follow the repeated positions. Leaving the old labels beside a larger output can hide which entries came from which input position. Preserve that connection when explaining the result.

Explain the expansion before continuing

A clear description names the input, the repetition counts, the selected axis and the output shape. For the first example, each of three values appears twice in a one-dimensional output. For the matrix examples, axis 1 expands columns, axis 0 expands rows and axis=None returns a flattened sequence.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Follow one input position and its repetition count at a time, then check the complete output arrangement before interpreting the values.

NumPy roll shifts positions with wraparound rather than creating empty entries

A shift does not always leave a blank space behind. NumPy roll moves entries along a selected axis and brings entries that pass the end back to the beginning. This circular arrangement preserves the values and the array shape. It is different from filling an exposed position with zero, marking it as missing or deleting an entry.

Academia Master Trader presents this lesson for English-language study in Guyana. The values are invented teaching numbers, not market observations or financial results. A short sequence makes the wraparound visible. A small matrix then shows why naming an axis matters when the same function is applied to more than one dimension.

Start with a sequence of four values

Let x be [3,6,9,12]. The expression np.roll(x,1) produces [12,3,6,9]. Each original entry moves forward by one position, and the final value 12 reappears at the beginning. The result still contains four values, with no new number introduced by the shift.

The number 1 is the shift argument. For this one-dimensional example, a positive shift moves values towards larger position numbers, with wraparound at the boundary. The original value at position 0 appears at position 1. The original final value cannot move beyond the available positions, so it returns to position 0.

Original diagram showing a one-position NumPy roll with the last entry wrapping to the beginning

Read a negative shift separately

The expression np.roll(x,-1) produces [6,9,12,3]. Now the first value reappears at the end. The sign changes the direction of movement along the selected axis. It does not change the values themselves or subtract one from every entry in the sequence.

With four positions, a shift of four gives the original arrangement. A shift of five gives the same arrangement as a shift of one. This follows from wrapping around the same four positions. Describing both the axis length and the shift makes a larger shift easier to interpret without drawing every intermediate step.

Follow a position through the wraparound

For a sequence of length four, an original position i moves to position (i+shift) modulo four. With shift=1, position 3 maps to position 0. That is where the final value 12 appears in the example. Modulo describes the circular boundary rather than a change to the stored value.

This coordinate rule also shows why roll is not a sort. If the input were [9,3,12,6], a shift of one would produce [6,9,3,12]. The function would keep the circular order instead of arranging entries by magnitude. Changing the values does not change the positional mapping.

Name the matrix axis explicitly

Let a have rows [2,4,6] and [8,10,12], with shape (2,3). The call np.roll(a,1,axis=1) shifts the column positions within each row. Its output has rows [6,2,4] and [12,8,10]. Each row wraps independently along its own length-three column axis.

The call np.roll(a,1,axis=0) instead shifts the row positions. Its output has rows [8,10,12] and [2,4,6]. Complete rows move together. The shape remains (2,3) in both cases, but the values occupy different coordinates because the selected axis is different.

Understand what happens when axis is omitted

The default axis is None. The NumPy documentation says the array is flattened before shifting and its original shape is restored afterwards. For the same matrix, np.roll(a,1) gives rows [12,2,4] and [6,8,10]. That differs from shifting each row independently along axis 1.

You can read that default result as a sequence operation: flatten the input to [2,4,6,8,10,12], roll it to [12,2,4,6,8,10], then restore two rows and three columns. Values can therefore cross a displayed row boundary when axis is omitted. The final shape does not tell you which mode was used.

Match multiple shifts to their axes

The documentation allows a tuple of shifts paired with a tuple of axes of the same size. The first shift belongs to the first named axis, the second to the second named axis, and so on. Keeping those pairs together in your explanation prevents a row shift from being described as a column shift.

For this matrix, np.roll(a,(1,1),axis=(0,1)) gives rows [12,8,10] and [6,2,4]. Both the row axis and the column axis have moved by one position. The documentation also allows one integer shift with several named axes, applying that same integer to each of them.

Keep circular shifts distinct from chronological delays

If a sequence represents observations in time order, wraparound has a specific consequence: the last observation can appear at the beginning. That is a property of a circular transformation, not evidence that a later observation was available earlier. The meaning of the data must remain separate from the mechanics of the array operation.

A delay that requires an empty or missing initial position is therefore a different requirement from circular wraparound. State which behaviour your calculation needs before choosing the operation. In this lesson, the output is deliberately circular, so every original teaching value remains present and no missing position is introduced.

Explain the result with its parameters

A clear description names the input shape, shift and axis. For the first example, four values move by one position and the final value wraps to the start. For the matrix, axis 1 shifts columns, axis 0 shifts rows and axis=None treats the entries as one flattened sequence before restoring the shape.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Keep the input beside the shifted output, follow the boundary entry and describe the wraparound before interpreting what the values mean.

NumPy rot90 turns a matrix through a chosen plane rather than sorting its values

A quarter-turn changes where values appear in a matrix. NumPy rot90 expresses that operation with a number of turns and an ordered pair of axes. For a two-dimensional array, the default call makes one counterclockwise quarter-turn. It changes the arrangement of the entries without comparing their sizes or calculating new numerical values.

Academia Master Trader presents this lesson for English-language study in Belize. The matrix uses invented teaching values, not prices or financial results. A rectangular example makes the change of shape visible. The aim is to connect a drawing with the function parameters so that the direction of the rotation can be explained precisely.

Start from a rectangular input

Let a have rows [2,5,8] and [11,14,17]. There are two rows and three columns, giving shape (2,3). Axis 0 identifies the rows and axis 1 identifies the columns. The first entry a[0,0] is 2, and the final entry a[1,2] is 17.

The default expression np.rot90(a) uses k=1 and axes=(0,1). The documentation describes the direction as from the first selected axis towards the second. For this usual two-dimensional drawing, that is counterclockwise. Naming both defaults keeps the meaning clear when later examples use a different axis order.

Original diagram comparing a two by three matrix with its counterclockwise quarter-turn using NumPy rot90

Read the first quarter-turn

The output of the default call has rows [8,17], [5,14] and [2,11]. Its shape is (3,2). The original final column becomes the first output row, the original middle column becomes the middle row and the original first column becomes the final row.

There are still six values. A quarter-turn of this rectangle exchanges the two side lengths, so the shape changes without changing the number of entries. This is different from an operation that creates an additional axis or removes a dimension. The output is still a two-dimensional matrix.

Follow a coordinate rather than a colour

In the input, the value 8 is at position [0,2]. After the default rotation, it appears at output position [0,0]. The value 11 begins at [1,0] and appears at output position [2,1]. These two mappings help establish the direction without relying on an arrow in a drawing.

For an input with two rows and three columns, output position [i,j] comes from input position [j,2-i] under this default quarter-turn. The expression describes the arrangement used here. It is not a comparison of the values, and changing a value would not change the coordinate mapping.

Let k count quarter-turns

The parameter k is the number of rotations by 90 degrees. With np.rot90(a,k=2), the result has rows [17,14,11] and [8,5,2]. That is a half-turn. Its shape is (2,3), because two quarter-turns bring the side lengths back to their original order.

With k=3, the rows are [11,2], [14,5] and [17,8], with shape (3,2). Four quarter-turns return the original arrangement of values. Tracking the output rows beside each k is more reliable than describing every call as a vague turn of the table.

Distinguish a negative turn from reversed axes

For the default axes, k=-1 gives one clockwise quarter-turn. In this example, the rows are [11,2], [14,5] and [17,8]. That is the same arrangement as three counterclockwise quarter-turns, although the parameter describes the direction in a different way.

The official documentation also explains that k=1 with axes=(1,0) reverses the direction of k=1 with axes=(0,1). It is equivalent to k=-1 with axes=(0,1). The order of the two axes therefore matters. The axes must be different; they are an ordered pair defining a plane, not an unordered set of labels.

Keep rotation separate from transposition

A transpose of the input would give rows [2,11], [5,14] and [8,17]. A default quarter-turn instead gives [8,17], [5,14] and [2,11]. Both have shape (3,2), but their values occupy different positions. Shape alone is not enough to identify which transformation was applied.

A written explanation should include the function name, k and axes, then show at least one coordinate mapping. That combination distinguishes a rotation from a transpose or a reversal. It also avoids suggesting that the function sorts rows into increasing or decreasing order.

Recognise the rotated view

The documentation describes the output as a rotated view. With a NumPy array input, this is different from making an independent copy of every entry. If b=np.rot90(a), editing through b can affect the corresponding input data. Follow the coordinate mapping when explaining which input entry an edit reaches.

For an ordinary writable NumPy array in this example, b[0,0] corresponds to a[0,2]. If you need a separate editable result, b=np.rot90(a).copy() explicitly makes a copy after the rotation. The choice between a view and a copy concerns how the data is shared, not which way the matrix appears to turn.

Name the plane in a larger array

The documented input requires two or more dimensions. For a three-dimensional input, the axes parameter selects which two axes define the rotation plane. A call using axes=(1,2) works in a different plane from a call using axes=(0,1). The unselected axis is not the axis pair being rotated.

Before interpreting such a result, write the complete input shape and identify the two selected axes. For odd quarter-turns, their lengths exchange places. Keep that structural description separate from the meaning attached to each dimension in your own dataset.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Keep the input beside the rotated view, state k and the ordered axes, and use the coordinates to explain where each value appears.

NumPy flipud reverses row order without reversing the values inside each row

Reversing a table can mean several different things. You might reverse the columns, reverse the rows or exchange the axes. NumPy flipud has a specific meaning: it reverses axis 0. In a two-dimensional matrix, that places the last row first and the first row last. Each complete row keeps its internal column order.

This Academia Master Trader lesson is written for English-language study in the Bahamas. All numbers are invented teaching values. They are not market observations or financial results. A small rectangular matrix makes the direction of the operation visible and helps keep positional changes separate from any interpretation of the data.

Identify axis 0 in the input

Let a contain the rows [7,14], [21,28] and [35,42]. The shape is (3,2), meaning three rows and two columns. Axis 0 has length three and identifies the row positions. Axis 1 has length two and identifies the column positions. NumPy numbers both axes and coordinates from zero.

The first row is therefore at position 0, the second at position 1 and the third at position 2. Reversing axis 0 means reading those row positions in the order 2,1,0. It does not mean reading each individual row from right to left. The selected axis tells you which order changes.

Original diagram showing NumPy flipud reversing three rows while preserving column order

Read the result as complete rows

The expression np.flipud(a) gives rows [35,42], [21,28] and [7,14]. The original third row appears first. The middle row remains in the middle. The original first row appears last. In every case, the first value in a row remains before the second value from that same row.

The output still has shape (3,2), with six values in total. Nothing has been added, removed or summed. The middle row stays in its position because this example has an odd number of rows. With an even number of rows, there is no single central row that maps to itself under the reversal.

Keep vertical reversal distinct from horizontal reversal

A horizontal reversal would exchange the two columns in this example. It would produce rows [14,7], [28,21] and [42,35]. That is not the output of flipud. Here the rows change order while the column positions within each row remain the same.

It is useful to describe the transformation with axis numbers as well as visual directions. Up and down make sense in a matrix drawing, but axis 0 identifies the operation precisely. The NumPy documentation gives np.flip(a,axis=0) as an equivalent expression. It also gives the slice a[::-1,...], which reverses the first axis and retains the others.

Follow one coordinate through the operation

In the input, the value 35 occupies a[2,0]. After reversal, it appears at output position [0,0]. The row coordinate changes from 2 to 0, while the column coordinate remains 0. Similarly, the input value 14 at [0,1] appears at output position [2,1].

For this three-row example, an output row i comes from input row 2 minus i. More generally, if axis 0 has length n, the corresponding input position is n minus 1 minus i. This positional mapping explains the result independently of the numerical values stored in the array.

Do not confuse reversal with a sort

The example starts with rows whose numbers increase from top to bottom. Reversing the rows therefore makes the displayed first-column values decrease. That does not mean flipud sorts the matrix. If the first-column values were 21,7 and 35, the reversed order would be 35,7 and 21.

The function follows the original positions from the end of axis 0 to the beginning. It does not compare values or choose which row deserves to come first. An explanation based on magnitude would fail as soon as the numbers changed, while an explanation based on axis 0 would remain correct.

Recognise that the result is a view

The official documentation describes flipud as returning a view. With a NumPy array input, the reversed view refers to the same underlying data rather than providing an independent copy of every value. If b=np.flipud(a), edits through b can therefore affect the corresponding entries in a.

For the ordinary writable NumPy array in this example, b[0,0] refers to the value originally at a[2,0]. Assigning 99 through that output position also changes the corresponding input data. If your next step requires an independent editable result, b=np.flipud(a).copy() explicitly adds a copy after the reversal.

Read one-dimensional and larger arrays by their axes

Unlike a function that specifically requires axis 1, flipud can work with a one-dimensional input. The documented requirement is at least one dimension. For a one-dimensional array [7,14,21], reversing axis 0 produces [21,14,7]. A scalar has no axis 0 and is outside that dimensional requirement.

For an array with shape (2,3,4), flipud still reverses axis 0. The two blocks along that first axis exchange order. The length-three and length-four axes keep their internal order. The name should not be read as a command to search for a visual vertical direction inside every matrix slice.

Keep the row labels with the rows

If rows carry labels, those labels explain what each row means. A presentation that reverses the data rows but keeps the labels in their old positions would attach the wrong labels to the values. The row labels must follow the same reversed order when they describe those rows.

Column labels do not need a reversed order for this two-dimensional operation, because axis 1 has not changed. State both parts together: rows reversed, columns preserved. That wording describes the example more clearly than saying that the table has simply been turned around.

Continue your study with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Keep the original matrix beside its reversed view, name axis 0 and follow one complete row at a time.

NumPy fliplr reverses column order while keeping each row together

A rectangular array can change its appearance without changing the values it contains. NumPy fliplr reverses the order along axis 1. For a two-dimensional matrix, that means the columns appear in the opposite order. Each row is read from its last entry to its first entry, while the order of the rows remains the same.

Academia Master Trader presents this lesson for English-language study in Barbados. The numbers are invented teaching values, not prices or financial results. A two-row example is enough to distinguish a left-to-right reversal from sorting, transposing or reversing a sequence through time. The key is to name the axis before describing the effect.

Give the input a clear structure

Let a have two rows: [4,8,12] and [16,20,24]. Its shape is (2,3). Axis 0 has length two and identifies the rows. Axis 1 has length three and identifies the columns. These lengths describe the arrangement, not the number of values in a particular category.

The first column contains 4 and 16. The second contains 8 and 20. The third contains 12 and 24. When fliplr reverses column order, those complete columns appear as third, second and first. The values within each column remain paired with their original row positions.

Original diagram showing NumPy fliplr reversing the columns of a two by three matrix

Read the reversed result row by row

The expression np.fliplr(a) produces rows [12,8,4] and [24,20,16]. The first row stays first and the second stays second. Within each row, the entry at the final column moves to the first displayed column, the middle entry stays in the middle and the original first entry appears last.

The shape remains (2,3). There are still two rows, three columns and six values. Nothing has been summed or removed. For this three-column example, the middle column remains in the middle because reversing three positions maps the central position to itself. An even number of columns would have no single central column.

Separate reversal from sorting

The first row of this example happens to start in increasing order, so its reversed form is decreasing. That is a property of the chosen values, not a sorting rule inside fliplr. If a row instead contains [8,4,12], reversing its column order gives [12,4,8]. The function follows positions rather than comparing magnitudes.

This distinction matters in written explanations. Say that axis 1 is reversed, then show the result. Saying that the function puts the largest values first would describe a different operation and would fail for the second row example. A good explanation should remain true when you replace the numbers but keep the same shape.

Keep reversal distinct from transposition

A transpose exchanges the roles of axes. A left-to-right reversal changes the order within one axis. In the example here, fliplr leaves the shape at (2,3). It does not turn two rows into three rows or turn the first row into the first column.

For a two-dimensional array, the official NumPy documentation gives the equivalent slice a[:,::-1]. The colon keeps the rows in their existing order, and the negative step reverses the column positions. The documentation also gives np.flip(a,axis=1) as an equivalent way to express the selected axis.

Understand the view before editing it

The documentation says fliplr returns a view. With a NumPy array as the input, this is different from creating an independent copy of all its values. If you name the result b=np.fliplr(a), changes through that view can affect the corresponding data in a. The changed position must be mapped through the reversed column order.

For this example, b[0,0] corresponds to a[0,2]. If a is an ordinary writable NumPy array, assigning 99 to b[0,0] also changes that entry in the shared input data. If you need a separate result before editing, b=np.fliplr(a).copy() explicitly adds a copy. Keep that distinction separate from the visual direction of the reversal.

Check the dimensional requirement

The input must have at least two dimensions. A one-dimensional array has axis 0, but it does not have axis 1. The name fliplr should therefore not be treated as a general instruction for reversing any list. Identify the shape of the object you actually have before choosing the function.

For an array with more than two dimensions, the operation still reverses axis 1. It does not automatically choose the last axis. If the shape is (2,3,4), the output has that same shape and the length-three axis is reversed. The length-four axis is not the axis selected by this function.

Keep labels aligned with the transformed data

In a study table, column labels explain what each column means. Reversing only the values while displaying the old labels unchanged would pair the values with different meanings. If the columns represent named variables, the labels need to follow the same new order in the presentation.

The same care applies to row labels. Since fliplr does not reverse axis 0, row labels remain in their original order for this two-dimensional example. Describe both decisions explicitly: columns reversed, rows preserved. That short explanation is clearer than describing the whole table as simply flipped.

Explain the result with one coordinate

A compact check is to follow the first output cell back to the input. Here the value 12 at output position [0,0] came from input position [0,2]. Once that mapping is clear, the remaining positions can be followed in the same way. The operation changes column order without making a claim about the meaning or quality of the values.

Continue your study with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Keep the original matrix beside the reversed view and name the axis whenever you explain how the positions changed.

NumPy tril preserves a lower triangular region rather than the smallest numbers

When a matrix is arranged in rows and columns, its diagonals describe positions. NumPy tril uses one of those diagonals as a boundary. It returns a copy in which entries above the selected diagonal become zero. Entries on that diagonal and below it keep their values. The word lower refers to their location in the matrix, not to how large or small those values are.

Academia Master Trader presents this lesson for English-language study in Trinidad and Tobago. The matrix contains invented teaching values. It does not represent an asset, a price series or a financial result. A small example lets you follow the coordinates directly and understand the transformation before applying it to a larger array.

Establish the input before reading the output

Let a have rows [5,10,15], [20,25,30] and [35,40,45]. There are three rows and three columns, so its shape is (3,3). NumPy coordinates start at zero. The entry a[0,0] is 5, a[1,1] is 25 and a[2,2] is 45. These positions form the main diagonal.

The values below that diagonal are 20,35 and 40. The values above it are 10,15 and 30. This positional description already tells you which region a default call to tril will retain. There is no need to compare one value with another to decide where the boundary falls.

Original diagram comparing a matrix with the lower triangular copy returned by NumPy tril

Follow the default boundary through the rows

The expression np.tril(a) uses the default k=0. Its result has rows [5,0,0], [20,25,0] and [35,40,45]. In the first row, only the main diagonal entry remains. In the second row, the first two entries remain. In the third row, every entry is on or below the main diagonal and therefore remains.

The output still has shape (3,3). It has not become a list containing only six numbers. Instead, it is a matrix with nine positions, three of which have been set to zero. Keeping shape and content separate makes the result easier to describe, particularly when another calculation expects a two-dimensional input.

Distinguish a boundary from a ranking

The value 35 remains because it occupies row 2, column 0, below the main diagonal. The smaller value 10 becomes zero because its position is row 0, column 1, above that diagonal. The function is not choosing the smallest values. It would use exactly the same positional boundary if those two values were changed.

For the default boundary, the preserved positions satisfy column j less than or equal to row i. With a general k, the rule becomes j minus i less than or equal to k. You can apply that rule to one coordinate at a time. It explains the lower triangular pattern without relying on the colour or arrangement of a particular drawing.

Move the boundary with a positive k

A positive k selects a diagonal above the main diagonal. For np.tril(a,k=1), the output rows are [5,10,0], [20,25,30] and [35,40,45]. The first diagonal above the main diagonal is now included. Only the position containing 15 sits above the selected boundary and becomes zero.

This is why a positive k can preserve more entries than the default call. It does not mean that the result shifts the original values into new cells. Every preserved value stays at its original coordinate. The change is in which coordinates qualify to remain, while all other coordinates in the output are filled with zero.

Move the boundary with a negative k

A negative k selects a diagonal below the main diagonal. For np.tril(a,k=-1), the output rows are [0,0,0], [20,0,0] and [35,40,0]. The main diagonal is above this new boundary and becomes zero along with the entries already above it. The preserved region is therefore smaller than it was with k=0.

Writing all three outputs beside their k values makes the difference clear. Zero includes the main diagonal. One includes a diagonal above it. Minus one excludes the main diagonal and begins with the diagonal below it. The sign describes the selected diagonal, not a command to add or subtract values from the matrix.

Retain the original when interpreting zeros

The official NumPy documentation describes the result as a copy with the same shape and data type as the input. Naming the output b=np.tril(a) keeps its role distinct from the input a. The call does not mean that a has been replaced by its lower triangular form.

A zero in the output is not always evidence that the function changed that cell. Some input cells may already contain zero. If the difference matters, compare the original matrix with the output using their coordinates and the selected k. The triangular copy carries the resulting values, not an explanation of the origin of each zero.

Identify the relevant axes in a larger array

The documented input shape allows different row and column counts. A square drawing is helpful for a first explanation, but tril also applies to rectangular matrices. The result keeps the input shape. A position is still judged against the diagonal boundary even when one dimension extends beyond the other.

For inputs with more than two dimensions, tril applies to the final two axes. Those axes define the matrix positions within each slice. Earlier axes distinguish the slices. Before interpreting such an output, write down its full shape and identify which two dimensions supply the rows and columns for the triangular operation.

Keep the explanation tied to the coordinates

A complete explanation of this example names the input, k=0 and the output rows. It says that entries above the main diagonal become zero while the main diagonal and lower region retain their values. It does not describe a sort, a sum or a selection based on magnitude.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Work through one row at a time, retain the input alongside the output and use the diagonal boundary to explain every preserved entry.

NumPy triu keeps the upper triangle without sorting matrix values

A matrix has a shape, an arrangement of values and a set of positions. NumPy triu works with those positions. It returns a copy in which entries below a chosen diagonal become zero. The entries on or above that boundary keep their original values. The operation does not rank numbers, calculate a total or change the order of the rows.

This Academia Master Trader lesson is written for English-language study in Jamaica. The example uses a small invented matrix so that each position can be followed by hand. Its numbers are teaching values, not observations from a market or results from a trading method. The goal is to understand a clear array operation before using it in a larger calculation.

Start with a matrix you can read

Let a contain the rows [3,6,9], [12,15,18] and [21,24,27]. Its shape is (3,3). The first coordinate identifies a row and the second identifies a column. Both coordinates start at zero. The main diagonal therefore contains a[0,0], a[1,1] and a[2,2], whose values are 3,15 and 27.

The upper triangle includes that main diagonal and the positions above it. For this matrix, those positions contain 3,6,9,15,18 and 27. The values 12,21 and 24 sit below the main diagonal. Recognising the coordinates first makes it easier to explain exactly what triu will preserve.

Original diagram showing the matrix and the upper triangular copy produced by NumPy triu

Read the default result row by row

The expression np.triu(a) uses k=0. Its output has rows [3,6,9], [0,15,18] and [0,0,27]. The first row has no positions below the main diagonal, so all its values remain. In the second row, the first position is below the diagonal and becomes zero. In the third row, the first two positions become zero.

The shape stays (3,3). This is an important distinction from extracting a diagonal into a one-dimensional array. The result still has nine positions. Some of those positions now contain zeros, while the preserved entries occupy their original row and column coordinates. A triangular matrix is not a shorter list of the values that remain.

Use k to move the boundary

The parameter k selects the diagonal that defines the boundary. A positive value moves it above the main diagonal. With np.triu(a,k=1), the output rows are [0,6,9], [0,0,18] and [0,0,0]. The main diagonal is now below the selected boundary, so its entries also become zero.

A negative value moves the boundary below the main diagonal. With np.triu(a,k=-1), the rows are [3,6,9], [12,15,18] and [0,24,27]. Only the value 21 is below that boundary in this example. These three results differ because k changes the position rule, not because NumPy compares the sizes of the numbers.

Separate position from magnitude

The value 27 remains in the default result because it lies on the main diagonal. The value 21 becomes zero because it lies below that diagonal. Replacing 21 with a much smaller number would not change the positional rule. Replacing it with a much larger number would not change the rule either.

For k=0, an entry at row i and column j is preserved when j is greater than or equal to i. More generally, the selected upper region follows j minus i greater than or equal to k. This coordinate description is useful when checking a handwritten result because it explains each cell independently of the matrix values.

Keep the copy separate from the input

The NumPy documentation describes triu as returning a copy. Calling b=np.triu(a) therefore gives you a separate result to name and inspect. The operation does not mean that the input variable a has been rewritten. Keeping both names available makes the transformation easy to explain alongside the original matrix.

It also keeps the purpose of a zero clear. A zero already present in the input and a zero introduced below the boundary may look identical in the output. The result alone does not record which kind each zero was. If that distinction matters to your work, retain the input and describe the positional rule with the result.

Read rectangular and higher-dimensional inputs carefully

The operation does not require a square matrix. Rows and columns can have different lengths while the same diagonal boundary is applied to their positions. A drawing of a square matrix is a convenient introduction, but it should not be turned into a requirement that the function does not have.

For an array with more than two dimensions, the official documentation says triu applies to the final two axes. Identify those axes before describing the result. An earlier axis can distinguish separate matrix slices, while the last two axes define the row and column positions within each slice. This prevents a diagram of one matrix from being mistaken for the complete shape of a larger array.

Explain the transformation before continuing

A useful written explanation names the input shape, the value of k and the output rows. For this example, the default result preserves the main diagonal and entries above it, introduces zeros below it and keeps the same shape. That description is more informative than saying that the data has simply been reduced.

Continue your study with Academia Master Trader at academiamastertrader.com.br. Aprenda brings you to the educational material. Keep the original matrix beside the triangular copy and follow one coordinate at a time to see why each entry remains or becomes zero.

NumPy diag extrae una diagonal o construye una matriz según la entrada

Una diagonal puede leerse como una secuencia de posiciones dentro de una matriz. En NumPy, diag tiene dos usos diferentes según la cantidad de dimensiones de su entrada. Con un arreglo de dos dimensiones, extrae una diagonal. Con un arreglo de una dimensión, construye una matriz que coloca esos valores sobre una diagonal.

La diferencia no depende del nombre de la variable ni de que los números aparezcan horizontalmente en pantalla. Depende de la forma real de la entrada. Por eso, antes de explicar una llamada a diag, conviene escribir si recibe una matriz o una secuencia unidimensional.

Extraer la diagonal principal

Consideremos una matriz a con tres filas: 2,4,6; 8,10,12; 14,16,18. Su forma es (3,3). La llamada diag sin otro argumento devuelve la secuencia 2,10,18. Son los valores situados donde coinciden el índice de fila y el índice de columna.

np.diag(a)

La diagonal principal corresponde a las posiciones [0,0], [1,1] y [2,2]. La salida contiene esos tres valores como un arreglo de una dimensión. No contiene todas las filas de la matriz ni una suma de los elementos seleccionados.

Esquema original: la matriz con filas 2,4,6; 8,10,12; 14,16,18 tiene diagonal principal 2,10,18. Se destacan las posiciones [0,0], [1,1] y [2,2].

La selección se basa en posiciones. Si se cambian los valores que ocupan esas posiciones, la diagonal extraída cambia con ellos. No se buscan los tres números mayores, los tres menores ni los elementos que cumplen una condición numérica externa.

El argumento k elige otra diagonal

El valor predeterminado de k es cero y señala la diagonal principal. Un k positivo indica una diagonal por encima de la principal. Un k negativo indica una diagonal por debajo. Cada desplazamiento se interpreta respecto de los índices de fila y columna de la matriz.

np.diag(a, k=1)

En nuestra matriz, k=1 devuelve 4,12. Son las posiciones [0,1] y [1,2]. La columna está una posición por delante de la fila. La salida tiene dos elementos porque esa diagonal llega al borde de la matriz después de esas dos posiciones.

np.diag(a, k=-1)

Con k=-1, la salida es 8,16, correspondiente a [1,0] y [2,1]. La diagonal comienza una fila debajo de la esquina superior izquierda. El signo indica el lado de la diagonal principal; no convierte los valores extraídos en positivos o negativos.

Construir una matriz desde una secuencia

Si la entrada es un arreglo x de una dimensión con valores 2,10,18, diag construye una matriz de dos dimensiones. Con el k predeterminado, las filas resultantes son 2,0,0; 0,10,0; 0,0,18.

np.diag(x)

Los valores de x se colocan en la diagonal principal y las demás posiciones contienen cero. Ahora la salida tiene forma (3,3), mientras que la entrada tenía forma (3,). La función está construyendo una matriz diagonal, no extrayendo datos de una matriz existente.

La diferencia entre extraer y construir explica por qué la misma función puede reducir o aumentar la cantidad de dimensiones en estos casos. La forma de entrada determina cuál de los dos usos se aplica. No debe describirse diag como una operación que siempre devuelve una secuencia.

Reconstruir no recupera toda la matriz

Extraer la diagonal principal de nuestra matriz a produce 2,10,18. Aplicar diag a esa secuencia produce una matriz con esos valores sobre la diagonal y ceros en las demás posiciones. No recupera los valores 4,6,8,12,14,16 que estaban fuera de la diagonal original.

np.diag(np.diag(a))

La salida de esa composición contiene solamente la información seleccionada por la extracción, colocada en una estructura nueva. Los valores externos a la diagonal ya no están en la secuencia intermedia. Construir una matriz diagonal no permite deducirlos ni volver a colocarlos automáticamente.

Esta lectura ayuda a distinguir una selección de una transformación reversible. Dos matrices diferentes pueden compartir la misma diagonal principal. Si se conserva únicamente esa diagonal, ya no se dispone de todos los elementos necesarios para identificar la matriz de origen.

Extraer no significa sumar

En nuestro ejemplo, diag devuelve la secuencia 2,10,18. La suma de esos valores sería 30, pero esa suma es otra operación. La documentación presenta trace como una función relacionada con sumar diagonales. Diag conserva los valores seleccionados como elementos separados de su salida.

La distinción importa cuando una etapa posterior espera una secuencia y otra espera un solo número. Ver que ambas operaciones se refieren a la diagonal no las convierte en intercambiables. El tipo de resultado y su forma deben acompañar la explicación de lo que se calculó.

Tampoco debe confundirse una diagonal con un triángulo de la matriz. La diagonal principal contiene una línea de posiciones con índices iguales. Los triángulos superior e inferior incluyen conjuntos más amplios de posiciones y corresponden a otras operaciones de selección.

Leer la forma antes del resultado

Una lectura ordenada comienza por la forma de entrada y continúa con el valor de k. Después identifica si la función extrae una secuencia o construye una matriz. Para explicar la selección, escriba algunas coordenadas junto con sus valores, en lugar de describir solamente una línea inclinada.

Academia Master Trader publica contenidos educativos sobre organización de datos y métodos numéricos. Visita academiamastertrader.com.br para conocer otros temas y continuar aprendiendo. Al leer diag, conserva la diferencia entre extraer, construir y sumar: cada acción produce una estructura distinta y responde a una pregunta diferente.

Aprenda

NumPy swapaxes intercambia dos ejes sin ordenar los valores por magnitud

Cambiar la posición de los ejes de un arreglo modifica cómo se escriben sus coordenadas. En NumPy, swapaxes intercambia dos ejes elegidos y conserva los demás en sus posiciones. La operación no compara valores para clasificarlos ni reemplaza unos números por otros.

Para interpretar el resultado conviene distinguir la identidad de un eje, su posición y su longitud. Un eje puede ocupar un lugar diferente en la forma sin cambiar la cantidad de posiciones que contiene. Si dos ejes tienen igual longitud, el intercambio puede incluso conservar la misma forma visible y aun así cambiar la correspondencia de coordenadas.

Dos filas pasan a ser dos columnas

Consideremos una matriz a con filas 2,4,6 y 8,10,12. Su forma es (2,3). Al intercambiar los ejes cero y uno, la salida tiene forma (3,2), con filas 2,8; 4,10; 6,12.

np.swapaxes(a, 0, 1)

El eje que tenía longitud dos pasa a la segunda posición, mientras que el de longitud tres pasa a la primera. La matriz resultante contiene los mismos seis elementos. La relación entre coordenadas se expresa como b[j,i] = a[i,j], si b es la salida del intercambio.

Esquema original: una matriz de forma (2,3), con filas 2,4,6 y 8,10,12, pasa a forma (3,2), con filas 2,8; 4,10; 6,12, al intercambiar sus dos ejes.

El esquema representa un intercambio de ejes, no una clasificación numérica. El valor 8 aparece junto al 2 en la primera fila de salida porque ambos compartían la primera posición de columna en filas distintas de la entrada. Su cercanía no depende de que uno sea mayor que otro.

En tres dimensiones se eligen dos ejes

Supongamos ahora que a tiene forma (2,3,4). Los ejes cero, uno y dos tienen longitudes dos, tres y cuatro, respectivamente. Intercambiar los ejes cero y dos produce una salida de forma (4,3,2).

np.swapaxes(a, 0, 2)

El eje uno permanece en su posición central. El orden de los ejes cambia de 0,1,2 a 2,1,0. Un elemento situado originalmente en a[i,j,k] aparece en b[k,j,i]. La coordenada central conserva su lugar y las coordenadas de los extremos intercambian sus posiciones.

La cantidad total de elementos sigue siendo veinticuatro. No se crea un eje adicional ni se elimina una dimensión de longitud uno. La forma cambia mediante una permutación de las longitudes que ya existían en el arreglo.

Una forma igual puede ocultar otro mapa

Consideremos una matriz cuadrada con filas 2,4 y 6,8. Su forma es (2,2). Al intercambiar los dos ejes, la salida tiene filas 2,6 y 4,8. La forma continúa siendo (2,2), pero la ubicación de los valores 4 y 6 cambia.

Esta situación muestra por qué comparar solo las formas no basta para describir una reorganización. Dos ejes pueden tener la misma longitud y representar coordenadas diferentes. El intercambio conserva esas longitudes, pero cambia qué índice se escribe primero y cuál se escribe después.

Si los ejes se llaman fila y columna, las etiquetas también deben acompañar la reorganización. Mantener nombres en el orden anterior puede producir una interpretación incorrecta incluso cuando la salida parece tener exactamente las dimensiones esperadas.

Intercambiar no es mover con desplazamiento

Desde la forma (2,3,4), swapaxes con los ejes cero y dos produce (4,3,2). En cambio, mover el eje cero al final mediante moveaxis produce (3,4,2). La diferencia está en lo que ocurre con el eje de longitud tres.

En el intercambio, ese eje se queda en su posición central. En el movimiento, conserva su orden relativo respecto del eje de longitud cuatro, y ambos quedan antes del eje trasladado. Por eso, elegir entre swapaxes y moveaxis depende del mapa de ejes buscado, no solamente de querer cambiar una dimensión de lugar.

Las dos operaciones pueden coincidir en algunos casos. En una matriz de dos dimensiones, intercambiar los dos ejes coincide con mover el primero al final. Esa coincidencia particular no convierte sus instrucciones generales en equivalentes para cualquier cantidad de dimensiones.

Los argumentos nombran posiciones de eje

Los números entregados a swapaxes identifican posiciones de ejes. No indican valores que deban buscarse entre los elementos ni filas particulares que se deban intercambiar dentro de una matriz. Intercambiar ejes cero y uno no significa intercambiar solamente la primera y la segunda fila.

En nuestra matriz de forma (2,3), cambiar dos filas conservaría esa forma. Intercambiar sus ejes produce (3,2). Son operaciones diferentes y la nueva forma permite reconocerlo en este ejemplo, aunque en una matriz cuadrada se necesite revisar también la correspondencia de coordenadas.

Antes de escribir la llamada, anote qué representa cada eje y cuáles posiciones se van a intercambiar. Después escriba el orden final completo. Esta descripción conserva el sentido de la operación cuando los arreglos tienen más dimensiones y ya no se explican fácilmente como una tabla.

Una vista puede compartir datos

Para una entrada que es un ndarray, la documentación actual indica que swapaxes devuelve una vista. No debe describirse como una copia independiente garantizada. Si se modifican valores mediante la vista, los datos correspondientes de la entrada pueden verse afectados.

Revisar la forma, el mapa de ejes y una relación de coordenadas permite leer la salida sin atribuirle una clasificación o una duplicación de información. Una misma cantidad de elementos puede representarse con otro orden de índices sin perder la relación con el arreglo original.

Academia Master Trader publica contenidos educativos sobre organización de datos y métodos numéricos. Visita academiamastertrader.com.br para conocer otros temas y continuar aprendiendo. Al leer swapaxes, sigue los dos ejes elegidos y conserva las etiquetas junto con las dimensiones que representan.

Aprenda

NumPy moveaxis cambia la posición de los ejes sin clasificar los valores

Un arreglo puede conservar sus datos y cambiar el orden de sus ejes. En NumPy, moveaxis mueve uno o varios ejes a nuevas posiciones. Los ejes que no se mueven mantienen su orden relativo. La función devuelve una vista del arreglo de entrada, no una copia independiente de sus valores.

Esta operación describe una reorganización de coordenadas. No ordena los elementos por magnitud ni desplaza una secuencia mediante posiciones vacías. Para leerla conviene identificar cada eje antes de mirar solamente la forma final, porque dos dimensiones con la misma longitud pueden representar cosas distintas.

Llevar el primer eje al final

Consideremos un arreglo a de forma (2,3,4). El eje cero tiene longitud dos, el eje uno tiene longitud tres y el eje dos tiene longitud cuatro. Al mover el eje cero a la última posición, la nueva forma es (3,4,2).

np.moveaxis(a, 0, -1)

El orden de los ejes pasa de 0,1,2 a 1,2,0. El eje de longitud dos no desaparece ni se convierte en un eje de longitud cuatro. Se coloca después de los otros dos, que conservan su orden relativo entre sí.

Esquema original: los ejes 0,1,2 de longitudes 2,3,4 pasan al orden 1,2,0 mediante moveaxis(a,0,-1); la forma cambia de (2,3,4) a (3,4,2).

La cantidad total de elementos permanece en veinticuatro. El cambio de forma refleja la posición nueva de las longitudes, no la creación o eliminación de datos. Leer cada longitud junto con la identidad de su eje ayuda a conservar la correspondencia entre la entrada y la salida.

Las coordenadas cambian de posición

En ese ejemplo, un valor situado en a[i,j,k] aparece en la salida en la posición [j,k,i]. El índice que antes se escribía primero pasa al final. Los otros índices mantienen su orden relativo, de acuerdo con el movimiento del eje cero.

b = np.moveaxis(a, 0, -1)

La relación b[j,k,i] = a[i,j,k] permite entender el resultado sin interpretar la operación como una mezcla de valores. Las mismas coordenadas siguen identificando el mismo elemento cuando se escriben en el orden correspondiente a los ejes reorganizados.

Si los ejes tenían etiquetas externas, como grupo, fila y columna, esas etiquetas deben moverse con ellos. No basta con conservar una lista de nombres en el orden anterior. La forma puede seguir siendo compatible con un cálculo y aun así interpretarse de manera equivocada si sus etiquetas quedan desalineadas.

Llevar el último eje al principio

Para el mismo arreglo de forma (2,3,4), mover el último eje al principio produce la forma (4,2,3). Ahora el orden de los ejes es 2,0,1. Los ejes que originalmente ocupaban las posiciones cero y uno permanecen en ese orden relativo.

np.moveaxis(a, -1, 0)

La posición negativa -1 indica el último eje. No significa que la longitud del eje sea negativa, ni que se deban invertir los valores que contiene. Es una manera de señalar una posición de eje desde el final de la estructura.

Este resultado es diferente de mover el primer eje al final. Las dos llamadas usan los extremos de la forma, pero no describen el mismo movimiento. Por eso, la explicación debe conservar por separado el origen y el destino, sin resumir ambas operaciones como cambiar los extremos.

No es un intercambio de dos ejes

Mover un eje y cambiarlo de lugar con otro eje pueden producir resultados distintos. Desde la forma (2,3,4), moveaxis con origen cero y destino dos produce (3,4,2). En cambio, intercambiar solamente los ejes cero y dos produce (4,3,2).

En el movimiento, el eje de longitud tres permanece antes que el de longitud cuatro. En el intercambio de los extremos, el eje de longitud tres queda en el centro y los otros dos cambian sus lugares entre sí. Son reorganizaciones diferentes, aunque ambas mantengan los mismos elementos.

La documentación presenta swapaxes como una función para intercambiar dos ejes y transpose como una función para permutar dimensiones. Elegir el nombre de la operación ayuda a describir qué orden se busca, en lugar de tratar todas las reorganizaciones como si fueran idénticas.

Varios ejes pueden moverse juntos

Moveaxis también admite secuencias de posiciones de origen y de destino. Cada secuencia debe contener posiciones únicas. Para nuestro arreglo de tres ejes, mover los ejes cero y dos a las posiciones dos y cero produce el orden 2,1,0 y la forma (4,3,2).

np.moveaxis(a, [0, 2], [2, 0])

Las correspondencias se leen por pares: el eje original cero va a la posición dos y el eje original dos va a la posición cero. El eje restante ocupa el lugar disponible. Conviene anotar ese mapa completo antes de interpretar los valores de salida.

La condición de posiciones únicas evita describir un destino repetido para distintos ejes dentro de la misma reorganización. La llamada representa una nueva disposición de los ejes existentes, no una instrucción para duplicar un eje ni para borrar otro que ocupe el mismo lugar.

Una vista conserva una relación con la entrada

Moveaxis devuelve una vista. Esto importa si una etapa posterior modifica los valores: los datos correspondientes del arreglo original pueden verse afectados. Cambiar la organización de los ejes no significa aislar la información en un almacenamiento nuevo e independiente.

Antes de continuar, registre la forma de entrada, el mapa de ejes y la forma de salida. Revise una correspondencia de coordenadas y mantenga las etiquetas externas en el mismo orden que los ejes. Esa lectura explica el movimiento sin confundirlo con una clasificación, una copia o una suma.

Academia Master Trader publica contenidos educativos sobre organización de datos y métodos numéricos. Visita academiamastertrader.com.br para conocer otros temas y continuar aprendiendo. Al leer moveaxis, sigue la identidad de cada eje y distingue su longitud de la posición que ocupa en la forma.

Aprenda