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 pad extends array boundaries using explicit widths and a chosen filling rule

Adding boundary entries changes an array's size and requires a rule for what those new positions contain. A zero border and a copied edge are different choices, even when they produce the same shape. Academia Master Trader explains NumPy pad in English for readers in North Macedonia. We will extend a short sequence and a small matrix, naming the widths and mode each time. Padding is an array construction rule, not a source of new measurements or evidence of financial performance.

Separate the input from its new boundary

After import numpy as np, define x = np.array([8,3,6]). The call np.pad(x,(1,2),mode='constant') returns [0,8,3,6,0,0]. The width pair means one position before the original sequence and two after it. Constant mode uses zero by default. The original entries remain together, in their original order, between the added boundaries.

The input shape is (3,), and the output shape is (6,). Its length is three original positions plus one before plus two after. Eight moves from original index zero to output index one because a new leading position was added. Three and six move by the same offset. Their relative order and numerical values remain unchanged.

Give constant padding an explicit value

The call np.pad(x,(1,2),mode='constant',constant_values=5) returns [5,8,3,6,5,5]. The widths have not changed, so the output length remains six. Only the filling rule's constant has changed from the default zero to five. The added five at the start is not an original observation, and neither are the two added fives at the end.

A padding width is a count of positions, whereas a constant value supplies their contents. Confusing those roles would produce a different array. Write the width pair and the constant separately when explaining a result. A reader should be able to identify which entries came from the input and which were introduced by the chosen boundary rule.

NumPy pad

Read the figure from the unchanged interior outward

The figure highlights the original sequence in gold inside both padded outputs. Begin with eight, three and six, then look at the single cell before them and the two cells after them. In the constant example those cells contain zeros. In the edge example they contain copies of the nearest boundary entries. The source block stays identical in both cases.

The figure's extra cells represent added array positions, not additional collected evidence. Keeping their colour separate from the original interior makes that distinction visible. Both examples have six entries, so their shapes alone cannot identify the selected mode. Inspect the boundary contents as well as the width counts before deciding what construction was used.

Use edge mode to extend the endpoint values

The call np.pad(x,(1,2),mode='edge') returns [8,8,3,6,6,6]. The leading added position copies the first entry eight. The two trailing added positions copy the last entry six. Original three remains between original eight and six. Edge mode does not repeat the whole three entry pattern, and it does not reverse the sequence.

The same widths therefore produce different outputs under constant and edge modes. Choosing a boundary rule is a modelling or processing decision, not something the input values alone determine. State it explicitly. A copied endpoint is still a copy, and a chosen constant is still a chosen constant; neither should be presented as a newly observed value outside the supplied sequence.

Specify widths for every matrix axis

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.pad(a,((1,0),(0,1)),mode='constant') returns [[0,0,0],[8,3,0],[2,9,0]], with shape (3,3). The first width pair adds one row before and none after. The second pair adds no column before and one after. All new positions contain the default constant zero.

The original eight is now at (1,0), while original nine is at (2,1). Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, a before and after width for each axis, and the selected mode. Then mark the original interior and verify the new boundary separately. Those checks explain the larger array without confusing added positions with new information.

NumPy tile repeats a whole array pattern rather than grouping copies of each entry

A repeated pattern preserves the order inside its source block. This differs from copying each entry several times before moving to the next one. Academia Master Trader explains NumPy tile in English for readers in Montenegro. We will tile a short sequence, add a row dimension and compare horizontal and vertical copies of a matrix. The expanded arrays contain repeated supplied values. They do not represent new observations, new measurements or evidence of financial performance.

Start with one complete pattern

After import numpy as np, define x = np.array([8,3,6]). The call np.tile(x,2) returns [8,3,6,8,3,6]. The original three entry sequence appears twice in the output. Its internal order remains eight, three, six in each appearance. The input shape is (3,), and the output shape is (6,).

The argument two specifies two total copies of the pattern, not two additional copies after the original. Separating the output visually into [8,3,6] followed by [8,3,6] makes that meaning explicit. Each original entry appears twice, but its appearances are separated by the other members of the pattern. This spacing is an important difference from consecutive entry repetition.

Compare tile with repeat using the same input

The call np.repeat(x,2) returns [8,8,3,3,6,6]. Its length is also six, but its grouping differs. Repeat places each value's copies next to one another. Tile copies the complete sequence before starting the next copy. Both operations expand this input, yet their outputs answer different arrangement requests.

For tile, output positions zero through two contain the first pattern and positions three through five contain the second. Eight occurs at indices zero and three. For repeat, eight occurs at zero and one instead. Track one original entry and the boundaries of its group before concluding that two similarly sized outputs are equivalent. A shared shape does not establish a shared order.

NumPy tile

Read the figure by complete blocks

The figure places the original sequence above the tiled result and the repeated entry result. Matching colours identify eight, three and six in each row. In the tiled row, read the colour sequence twice from left to right. In the repeat row, read adjacent pairs of each colour. The same original values appear in both rows, but their positions explain the difference.

All displayed numbers come from the original sequence. Repetition does not add information about a population or a time period merely by increasing the number of entries. If these values represented observations, copied appearances would still be copies. Keep the source block and the repetition rule visible whenever a larger array is used to illustrate structure.

Give a repetition count for each dimension

The call np.tile(x,(2,2)) returns [[8,3,6,8,3,6],[8,3,6,8,3,6]], with shape (2,6). The two supplied repetition counts describe a two dimensional arrangement. NumPy treats the one dimensional source as shape (1,3) for this operation, adding a leading axis. The first count creates two rows, and the second count places two source patterns along each row.

The original x remains a one dimensional array; this promotion describes how tile interprets it while constructing the result. It is not a change to x itself. Writing the promoted shape (1,3) before the final shape (2,6) helps explain why two repetition counts can produce a two dimensional result from a one dimensional input.

Distinguish horizontal and vertical matrix copies

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.tile(a,(1,2)) returns [[8,3,8,3],[2,9,2,9]], with shape (2,4). It copies the whole matrix horizontally. By contrast, np.tile(a,(2,1)) returns [[8,3],[2,9],[8,3],[2,9]], with shape (4,2), copying the whole matrix vertically.

For this two dimensional source, np.tile(a,2) is equivalent to the horizontal case because the shorter repetition specification is given a leading one. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source shape, repetition counts and complete block boundaries. Those checks keep pattern copies distinct from entry copies and make the resulting dimensions clear.

NumPy repeat duplicates entries or slices along a chosen axis rather than repeating an entire pattern

Repeating each entry is different from writing a whole sequence again. The distinction matters when an array grows and the position of each copy needs to stay clear. Academia Master Trader explains NumPy repeat in English for readers in Serbia. We will begin with a short sequence, then repeat rows and columns of a matrix. The extra entries are copies of supplied values. They are not new observations, additional measurements or evidence of financial performance.

Repeat each sequence entry consecutively

After import numpy as np, define x = np.array([8,3,6]). The call np.repeat(x,2) returns [8,8,3,3,6,6]. Each original entry appears twice before the operation moves to the next original entry. The input has shape (3,), and this output has shape (6,). A repetition count of two means two total appearances, not the original plus two additional copies.

The result is not [8,3,6,8,3,6]. That arrangement repeats the entire three entry pattern. NumPy repeat instead keeps each entry's repetitions adjacent. Follow the first value eight: its two output positions are zero and one. Three then occupies two and three, while six occupies four and five. This positional account identifies the operation more clearly than the shared output length alone.

Give different counts to different entries

The call np.repeat(x,[1,2,3]) returns [8,3,3,6,6,6]. Eight appears once, three twice and six three times. The counts describe each original position in order. The output length is the sum of those counts, so it is six in this example. The repeated groups preserve the order of the original entries.

A zero count contributes no copy of that entry. For example, np.repeat(x,[1,0,2]) returns [8,6,6]. Three is omitted because its specified count is zero, not because of its numerical size or a comparison with neighbouring values. Use compatible counts for the chosen input or axis. Naming the counts and their positions prevents a reader from interpreting them as new values to insert.

NumPy repeat

Read the figure as groups of copies

The figure shows the original sequence above the two repetition results. Matching colours connect each original entry with its output group. In the equal count result, every colour occupies two adjacent cells. In the unequal count result, the coloured groups have lengths one, two and three. Read group lengths rather than treating repeated numbers as independent measurements.

Both illustrated outputs have six entries, but they use different repetition rules. Equal output length does not establish equal content or equal grouping. The first output contains two eights; the second contains one eight. Keeping the repetition counts next to the output makes that distinction visible. The copied values retain their original numerical meaning even though their number of appearances changes.

Repeat complete rows or columns

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.repeat(a,2,axis=0) returns [[8,3],[8,3],[2,9],[2,9]], with shape (4,2). Axis zero selects rows as the slices being repeated. The first complete row appears twice, followed by two appearances of the second complete row. The column count remains two.

The call np.repeat(a,2,axis=1) returns [[8,8,3,3],[2,2,9,9]], with shape (2,4). Now columns are repeated, so each row contains adjacent pairs. The number of rows remains two. Because the input is square, its original shape does not identify which direction will grow. The axis argument and the resulting shape show which dimension changed.

State the default flattening rule

If axis is omitted, NumPy uses the flattened input and returns a flat output. For our matrix, np.repeat(a,2) returns [8,8,3,3,2,2,9,9], with shape (8,). It does not preserve the two dimensional layout. That differs from explicitly repeating along either matrix axis, even though all three calls copy the same supplied values.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, repetition counts and axis before writing the result. Then follow one original entry or complete slice through its output group. These checks distinguish consecutive repetition from pattern repetition and keep copied data separate from genuinely new observations.

NumPy roll shifts array entries cyclically and wraps them around the selected axis

A cyclic shift moves values to new positions while returning entries that pass an edge to the other end. That boundary rule distinguishes it from inserting empty cells or discarding old observations. Academia Master Trader explains NumPy roll in English for readers in Bosnia and Herzegovina. We will follow a small sequence and a rectangular matrix, keeping the shift and axis explicit. These examples change arrangements only. They do not generate new measurements, forecasts or evidence of financial performance.

Begin with a sequence and one positive step

After import numpy as np, define x = np.array([8,3,6,2]). The call np.roll(x,1) returns [2,8,3,6]. Each entry advances one position along the sequence. Two starts at the last index, passes the right edge and returns at index zero. Eight moves from zero to one, three moves from one to two and six moves from two to three.

The output still has four entries. No zero is inserted at the beginning, and the former last value is not dropped. The wraparound is part of the operation, not a detail to add later. Writing both the original last entry and the new first entry makes the boundary behaviour visible before examining the other positions.

Use a negative shift for the opposite direction

The call np.roll(x,-1) returns [3,6,2,8]. Now each entry moves one position toward smaller indices, with eight returning at the last index. A negative shift changes the direction of movement; it does not make the values negative. The numerical entries remain eight, three, six and two in a new cyclic arrangement.

A shift equal to the sequence length returns the original arrangement. Thus np.roll(x,4) gives [8,3,6,2], and np.roll(x,5) gives the same arrangement as a positive one step shift. The effective movement depends on the shift relative to the axis length. This is a positional property, not an arithmetic change applied to each entry.

NumPy roll

Read the figure at the wraparound boundary

The figure displays the original four entry sequence, the positive one step result and the negative one step result. Matching colours track eight and two between the ends. For the positive shift, original two becomes the first entry. For the negative shift, original eight becomes the last entry. Read those edge movements before following the inner entries.

All three displayed sequences contain the same values and have shape (4,). Their sums are equal because no entry was inserted or removed. Equal sums do not identify which shift was used, however. Compare the ordered entries and state the shift. A summary total cannot replace the positional evidence that explains a cyclic arrangement.

Choose an axis for a matrix

Define a = np.array([[8,3,6],[2,9,4]]), with shape (2,3). The call np.roll(a,1,axis=1) returns [[6,8,3],[4,2,9]]. Each row shifts cyclically across its columns. Six wraps from the end of row zero to its beginning, and four wraps within row one. Values remain in their original rows because the chosen axis is the column axis.

The call np.roll(a,1,axis=0) instead returns [[2,9,4],[8,3,6]]. Complete rows change position. There are two rows, so moving one row forward exchanges their places. The order inside each row stays unchanged. Both matrix outputs have shape (2,3), but their values occupy different coordinates because the selected axes differ.

Do not leave the default axis implicit

When axis is omitted, NumPy flattens the input for the shift and then restores the original shape. For our matrix, np.roll(a,1) returns [[4,8,3],[6,2,9]]. This is different from shifting each row separately. Four moves from the final flattened position to the beginning, and six crosses the displayed boundary between the original rows.

That default is useful when the intended operation concerns the flattened sequence, but it should be stated rather than assumed. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape, shift and axis, then follow an entry through the relevant edge. These checks distinguish a cyclic shift from a reversal, a transpose or a shift that pads missing positions.

NumPy rot90 turns a rectangular array by a quarter turn with a defined direction

A quarter turn changes the positions of rows and columns together. It is different from reversing only one axis or exchanging row and column roles without the appropriate reversal. Academia Master Trader explains NumPy rot90 in English for readers in Albania. We will follow a small rectangular matrix through one counterclockwise turn, a clockwise turn and a half turn. Every output uses the original values. These examples concern array arrangements, not predictions, additional observations or evidence of financial performance.

Record the input before naming a direction

After import numpy as np, define a = np.array([[8,3,6],[2,9,4]]). Its shape is (2,3), with two rows and three columns. The first row contains eight, three and six. The second row contains two, nine and four. Recording this layout gives a fixed reference for words such as clockwise, counterclockwise, upper and lower.

The default call np.rot90(a) returns [[6,4],[3,9],[8,2]], with shape (3,2). This is one counterclockwise quarter turn in the default plane of axes (0,1). Original column two, containing six above four, becomes the first output row. Original column one becomes the second output row, and original column zero becomes the last output row.

Follow the corners through the turn

The original upper right entry six at (0,2) becomes the output upper left entry at (0,0). Original lower right entry four at (1,2) becomes output upper right at (0,1). Original upper left entry eight at (0,0) becomes output lower left at (2,0). These corner movements are consistent with a counterclockwise turn of the displayed matrix.

For this default two dimensional quarter turn, an original position (i,j) maps to (n-1-j,i), where n is the original number of columns. Here n equals three. The input position (1,1), containing nine, therefore maps to (1,1). That coincidence belongs to this particular rectangular shape and position; it does not mean that rotation leaves every middle entry at unchanged coordinates.

NumPy rot90

Read the figure as a change of layout

The figure puts the two by three input beside the three by two default result. Matching colours track the original first and last columns into the last and first output rows. Read those groups as complete pairs. Eight and two remain associated as a pair, but now appear next to each other rather than one above the other.

The figure is a positional explanation, not a plot with a measured horizontal or vertical scale. Every cell contains one original entry, and the number of cells stays six. The output shape changes because the rectangular layout turns, not because values were added or removed. A square example would keep the same shape after a quarter turn, making coordinate tracking even more useful.

Compare clockwise and half turns

The call np.rot90(a,k=-1) returns [[2,8],[9,3],[4,6]]. A negative one requests one quarter turn in the reverse direction, clockwise for the default axes. Its shape is also (3,2), so shape alone cannot tell clockwise from counterclockwise. The first row distinguishes them: two then eight for the clockwise result, six then four for the default counterclockwise result.

The call np.rot90(a,k=2) returns [[4,9,2],[6,3,8]], with shape (2,3). Two quarter turns make a half turn. Both the order of rows and the order within each row are reversed relative to the input. Four quarter turns return the original arrangement. The parameter k counts quarter turns; it is not a request to rotate by k degrees.

Keep the axes and shared data explicit

NumPy rot90 requires at least two dimensions, and the two chosen axes must be different. For a two dimensional input, changing axes=(0,1) to axes=(1,0) reverses the rotation direction. State both k and the axes when describing a result, especially for arrays with more than two dimensions, where the selected plane matters.

The documented result is a rotated view that shares data with its source. Use .copy() when an independent result is needed before later edits. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the original shape, name the direction and follow two corners. These checks distinguish a quarter turn from a transpose or a single axis reversal without changing the meaning of the supplied values.

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

The direction of an array reversal matters. Moving a bottom row to the top is different from reading each row from right to left. Academia Master Trader explains NumPy flipud in English for readers in Greece. This lesson follows a three row matrix, records coordinate changes and compares vertical reversal with other familiar arrangements. All supplied values remain present. The example describes array structure and does not create new observations, predictions or evidence of financial performance.

Begin with a rectangular input

After import numpy as np, define a = np.array([[8,3],[2,9],[6,4]]). Its shape is (3,2): three rows and two columns. Row zero contains eight followed by three, row one contains two followed by nine and row two contains six followed by four. Writing the complete input avoids treating a vertical list of numbers as though it were a horizontal row.

The call b = np.flipud(a) returns [[6,4],[2,9],[8,3]], still with shape (3,2). Original row two becomes output row zero. Original row zero becomes output row two. The middle row stays in the middle. Each row preserves its own internal left to right order. Six still precedes four in their row, and eight still precedes three in theirs.

Track row coordinates rather than numerical size

Eight moves from input position (0,0) to output position (2,0). Three moves from (0,1) to (2,1). The column coordinate does not change. Likewise, six moves from (2,0) to (0,0) and four moves from (2,1) to (0,1). These movements follow row position rather than the size of each value.

For an input with m rows, the row mapping is i -> m-1-i. With three rows, this maps zero to two, one to one and two to zero. The middle row is fixed in this example because the number of rows is odd. With an even number of rows, there is no single central row index that maps to itself. The same mapping rule still applies.

NumPy flipud

Read the figure from complete row to complete row

The figure places the original and reversed matrices side by side. Matching row colours identify the row containing eight and three and the row containing six and four. Read each coloured row as a pair. The upper original pair appears at the bottom of the result, while the lower original pair appears at the top. The two middle entries keep their middle row.

The shape labels stay three by two. Reversal neither adds a row nor removes a column. Looking down original column zero gives eight, two, six; looking down output column zero gives six, two, eight. This is the vertical counterpart of the row mapping. The total of all entries is unchanged because every input value appears exactly once in the output.

Compare with horizontal reversal and transpose

For the same a, np.fliplr(a) returns [[3,8],[9,2],[4,6]]. It reverses the order of columns, not the order of rows. Its first row contains three and eight, while the first row of our flipud result contains six and four. Both results have the input shape, so their shapes alone do not distinguish the direction. The coordinate changes do.

The transpose a.T is different again: it returns [[8,2,6],[3,9,4]] with shape (2,3). It exchanges the roles of rows and columns. Our vertical reversal remains three by two. Name the operation before interpreting a displayed matrix as a rotation or transpose. Similar looking arrangements can arise from different rules, especially when an input has repeated values or symmetry.

Keep the view and input requirements clear

NumPy flipud accepts an input with at least one dimension. For np.array([8,3,6]), it returns [6,3,8]. That one dimensional case reverses the sequence along axis zero; it does not create a second dimension. In the matrix example, axis zero corresponds to the row order we followed.

The documented output is a view that shares data with the input. Use .copy() when you need an independent result for later edits. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the shape, follow the top and bottom rows and check that column coordinates stay fixed. Those steps make vertical reversal clear without confusing a change in position with a change in value.

NumPy fliplr reverses column order while keeping each row in its original position

A left to right reversal changes where columns appear, without changing the values stored in those columns. Academia Master Trader explains NumPy fliplr in English for readers in Bulgaria. We will use a rectangular array, track individual coordinates and separate horizontal reversal from a transpose or an up to down reversal. Every number in the output already exists in the input. The example describes a change in arrangement, not a forecast, new observations or evidence of financial performance.

Write the input as two complete rows

After import numpy as np, define a = np.array([[8,3,6],[2,9,4]]). The input has shape (2,3), meaning two rows and three columns. Row zero contains eight, three and six in that order. Row one contains two, nine and four. Recording the rows before applying a transformation makes it easier to tell which direction changes.

The call b = np.fliplr(a) gives [[6,3,8],[4,9,2]]. The shape remains (2,3). Row zero is still the first row, but its column order is reversed. Row one is still the second row and its column order is reversed too. Each row keeps the same members. No value crosses from the first row into the second row during this operation.

Follow the column mapping explicitly

For an input with three columns, original column zero becomes output column two, original column one remains in the middle and original column two becomes output column zero. Eight therefore moves from (0,0) to (0,2), while six moves from (0,2) to (0,0). The row coordinate stays zero in both cases.

In the second row, two moves from (1,0) to (1,2) and four moves from (1,2) to (1,0). Nine remains at (1,1), because the middle column of a three column array maps to itself. For a width of n columns, the general column rule is j -> n-1-j. The row coordinate remains unchanged. This rule explains both the moving edge columns and the fixed middle column here.

NumPy fliplr

Read the figure row by row

The figure places the original array beside the horizontally reversed result. Read the top row on the left as eight, three, six and its counterpart on the right as six, three, eight. Then read the second row separately. Its left side is two, nine, four and its right side is four, nine, two. The shared shape label confirms that neither dimension changed.

The highlighted edge columns make the mapping easier to see. The leftmost original column contains eight above two; the rightmost output column contains those same values in the same vertical order. A whole column changes its horizontal position while its entries keep their row positions. The total of all six entries also stays unchanged, because the operation rearranges values rather than adding or removing them.

Separate reversal from a transpose

The expression a.T returns [[8,2],[3,9],[6,4]], with shape (3,2). That is a transpose, which exchanges row and column roles. It is not the result of fliplr. Comparing shapes is especially useful for this rectangular example: the horizontal reversal stays two by three, while the transpose becomes three by two.

An up to down reversal is different again. The call np.flipud(a) returns [[2,9,4],[8,3,6]]. It reverses the order of rows while preserving the order inside each row. The first row of that output starts with two, whereas the first row of our fliplr output starts with six. Name the operation and its changing axis before describing a result simply as reversed.

Remember the input requirement and shared data

NumPy fliplr requires at least two dimensions. A flat array such as np.array([8,3,6]) does not meet that requirement. A one row matrix such as np.array([[8,3,6]]) does, and its reversed result is [[6,3,8]]. The extra row structure is meaningful even when there is only one row.

The documented result is a view, so it shares data with the source array. Use .copy() when an independent result is needed before later edits. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape, check both edge columns and follow a middle entry. Those checks explain the reversal without confusing it with a rotation, transpose or change in numerical values.

NumPy trace adds the entries on a chosen diagonal rather than returning the diagonal sequence

Reading a matrix diagonal and adding its entries are different operations. One preserves an ordered sequence, while the other produces a total for that selected diagonal. Academia Master Trader explains NumPy trace in English for readers in Hungary. We will begin with a three by three matrix, identify coordinates and then calculate the main trace and two offset traces. The arithmetic uses only the supplied integers. These examples describe array operations, not financial performance, a forecast or additional observations beyond the input.

Record the full input and selected positions

After import numpy as np, define a = np.array([[8,3,6],[2,9,4],[7,5,1]]). Its shape is (3,3), with row and column indices from zero through two. The main diagonal contains eight at (0,0), nine at (1,1) and one at (2,2). These pairs share the same row and column index. None of the other six positions belongs to this main diagonal.

The call np.trace(a) returns 18, because 8 + 9 + 1 = 18. For this two dimensional input, the result is a single sum rather than an array containing three separate diagonal entries. The operation selects the diagonal according to its coordinates and then adds the selected values. Naming both steps makes clear why a value outside the diagonal does not contribute.

Distinguish the trace from the diagonal sequence

For the same input, np.diagonal(a) returns [8,9,1], while np.trace(a) returns 18. The three entry sequence and its total are related, but they are not interchangeable descriptions of an output. The sequence keeps the individual values visible. The sum combines them into one result, which no longer records their original order as separate entries.

Different diagonal sequences can have the same sum. The sequence [7,8,3] also adds to eighteen, but it is not the main diagonal of our input. Knowing the trace alone therefore does not recover every contributing entry. Keep the source matrix or the selected coordinate pairs beside the total when explaining where it came from. The total is a summary of selected values, not a complete description of their arrangement.

NumPy trace

Read the figure as selection followed by addition

The figure highlights the main diagonal inside the input matrix and places the sum beside it. Read the highlighted coordinates in increasing row order: (0,0), (1,1) and (2,2). Their values are eight, nine and one. The displayed eighteen is the result of their addition, not a tenth input cell or a replacement value inserted into the original matrix.

The largest supplied entry, nine, contributes because it lies on the selected diagonal. One contributes for exactly the same positional reason. Seven does not contribute to this call because it occupies (2,0), outside the main diagonal. A trace is therefore not the sum of the largest numbers, a row total or a column total. The coordinate selection comes before the arithmetic.

Add an upper offset diagonal

The call np.trace(a,offset=1) returns 7. It adds three at (0,1) and four at (1,2), so 3 + 4 = 7. The column index is one greater than the row index at both positions. This selects the first diagonal above the main diagonal. Only two matching positions fit inside this matrix, so only those two entries contribute.

A positive offset does not add one to the main trace, nor does it move all input values. It chooses a different diagonal before performing the sum. For offset=2, the only contributing position is (0,2), containing six, so the result is six. The matrix dimensions explain why that diagonal has only one entry in this example.

Add a lower offset diagonal

The call np.trace(a,offset=-1) returns 7 as well, this time from two at (1,0) and five at (2,1). The sum is 2 + 5 = 7. This equals the upper offset total numerically, but the contributing coordinates and values are different. Equal results do not establish that the same diagonal was selected.

A rectangular input works too. For b = np.array([[8,3,6],[2,9,4]]), np.trace(b) returns seventeen from eight and nine. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape and offset, list contributing positions and write the addition explicitly. Those checks keep a diagonal total distinct from its source sequence and from sums over other regions.

NumPy tril preserves the lower region of a matrix and zeros positions above its diagonal boundary

An array's lower triangle is defined by row and column positions. It is not a collection of the smallest numbers, and keeping it does not mean deleting the upper rows. Academia Master Trader explains NumPy tril in English for readers in Romania. We will read a three by three matrix, mark the default boundary and compare two shifted boundaries. The supplied entries make every output directly checkable. These examples concern data organisation, not financial outcomes or additional observations. The distinction between a retained value and a replacement zero will guide the explanation.

Identify the main diagonal

After import numpy as np, define a = np.array([[8,3,6],[2,9,4],[7,5,1]]). Its shape is (3,3). Row and column indices each run from zero through two. The main diagonal connects positions (0,0), (1,1) and (2,2), containing eight, nine and one. A position below this diagonal has a row index greater than its column index. A position above it has the opposite relationship.

The call np.tril(a) gives [[8,0,0],[2,9,0],[7,5,1]], with the same shape (3,3). It retains entries on and below the main diagonal and replaces entries above it with zeros. Three, six and four are replaced in their respective output positions. The retained values stay at their original coordinates, so two remains at (1,0) and five remains at (2,1).

Keep every row and column position

The first output row is [8,0,0], not simply [8]. Its two zeros preserve the second and third column positions. The second row is [2,9,0], while the final row remains [7,5,1]. All nine positions still exist in the output. Reading the result as three rows of different lengths would describe a different structure from the actual three by three array.

NumPy documents tril as returning a copy whose entries above the selected diagonal are zeroed. In this example, the original matrix supplies all retained numbers, while the zeros describe the operation's replacement rule. They do not mean the original observations at those coordinates were zero. The function also does not move selected entries together to form a compact one dimensional sequence.

NumPy tril

Read the lower region in the figure

The figure shows the complete input beside the default output. Gold cells in the output contain retained entries; grey cells contain replacement zeros. Follow seven at (2,0). It is below the main diagonal and stays seven at that coordinate. Follow six at (0,2). It is above the main diagonal, so its corresponding output position contains zero.

The largest supplied number, nine, remains because it sits on the main diagonal. One remains for the same positional reason. Seven is retained even though it is larger than several entries that are replaced. This makes the rule different from keeping values below a numerical threshold. Coordinates decide which positions are zeroed, independently of the relative sizes of their contents.

Use a negative k for a stricter lower region

The call np.tril(a,k=-1) gives [[0,0,0],[2,0,0],[7,5,0]]. The selected boundary is the first diagonal below the main diagonal. Entries on the main diagonal are now above that boundary, so eight, nine and one are zeroed as well. The retained entries are two, seven and five. The shape is still (3,3) because the boundary changes the retained region, not the dimensions.

A negative k is not a request for negative numerical values. Our input contains only positive integers, yet this call has a clear result. It also does not subtract one from any retained entry. Two stays two, seven stays seven and five stays five. Write the chosen diagonal beside the matrix before interpreting the sign as an instruction about arithmetic.

Use a positive k to retain more positions

The call np.tril(a,k=1) gives [[8,3,0],[2,9,4],[7,5,1]]. It includes the first diagonal above the main diagonal as well as everything below it. Only six, at (0,2), is above the selected boundary and is replaced. With k=2, all entries of this particular matrix are retained. That statement depends on its dimensions, rather than being a general promise about every input.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape and k value, mark the diagonal boundary and write a zero in every output position above it. Then trace two retained coordinates to confirm that their values and positions remain unchanged.

NumPy triu keeps an upper triangle while replacing entries below its boundary with zeros

A triangular arrangement in an array concerns coordinates rather than the size of the numbers. Keeping the upper triangle does not mean keeping the largest values. Academia Master Trader explains NumPy triu in English for readers in Croatia. We will use a small matrix to follow the main boundary and then move that boundary with the k argument. Every result can be checked against the input positions. These examples describe data organisation, not financial outcomes, forecasts or additional observations beyond the supplied integers.

Write the complete input first

After import numpy as np, define a = np.array([[8,3,6],[2,9,4],[7,5,1]]). Its shape is (3,3), with three rows and three columns. Both sets of indices run from zero through two. The main diagonal contains eight at (0,0), nine at (1,1) and one at (2,2). Entries above that diagonal have a column index greater than their row index.

The call np.triu(a) returns [[8,3,6],[0,9,4],[0,0,1]], also with shape (3,3). It keeps entries on and above the main diagonal and replaces entries below it with zeros. The input positions containing two, seven and five correspond to zeros in the output. Other values stay at their original coordinates. No row or column is removed from the result. The output still contains nine positions, including the three positions now occupied by replacement zeros.

Distinguish a zeroed position from an omitted position

The second output row is [0,9,4], not [9,4]. Its initial zero preserves the first column position. The final row is [0,0,1], preserving all three column positions even though only one original value remains there. These zeros are part of the returned arrangement. They are not evidence that the original data contained zero observations at those positions.

The documentation describes triu as returning a copy with entries below the selected diagonal zeroed. For this operation, reading the output should therefore not be confused with deleting parts of the original matrix. In our example, the shape remains three by three and the retained values do not move. The operation changes specified output entries rather than producing a compact list of selected values.

NumPy triu

Read the figure by coordinates

The figure places the input beside the result for the default boundary. Gold cells identify the retained upper region in the result; grey cells contain the replacement zeros below it. Follow four at (1,2). Its column index is greater than its row index, so it remains four at the same output coordinate. Two, at (1,0), is below the boundary and becomes zero in the output.

Nine is kept because of its position on the main diagonal, not because it is the largest supplied number. One is kept for exactly the same positional reason. Seven is larger than one but lies below the boundary, so its output position becomes zero. This contrast separates a geometric rule from a numerical ranking or a threshold applied to the values.

Move the boundary above the main diagonal

The call np.triu(a,k=1) gives [[0,3,6],[0,0,4],[0,0,0]]. Only entries above the main diagonal are retained. The main diagonal itself is now below the selected first upper diagonal and is zeroed. The shape remains (3,3). A positive k moves the retention boundary upwards in the familiar printed matrix layout; it does not add one to the retained values.

For k=2, only six remains from this input, giving [[0,0,6],[0,0,0],[0,0,0]]. The value six occupies (0,2), on the second upper diagonal. There is no additional entry further along that diagonal within the matrix. This example makes the selected boundary visible without changing the input dimensions.

Move the boundary below the main diagonal

The call np.triu(a,k=-1) gives [[8,3,6],[2,9,4],[0,5,1]]. It retains the first diagonal below the main diagonal as well as everything above it. Only seven at (2,0) remains below the selected boundary and is zeroed. A negative k changes the boundary position; it does not request negative numerical entries or subtract from the retained numbers.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape and k value. Mark the retained coordinates, write replacement zeros in the remaining positions and confirm that the full shape is preserved. Those checks explain the upper triangle without confusing it with sorting or removing rows.