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 triu retains an upper triangular region without shrinking the matrix

An upper triangular selection keeps positions on one side of a diagonal boundary. NumPy triu preserves those entries and replaces positions below the boundary with zero. Academia Master Trader presents this English lesson for readers in Eritrea, using constructed arrays to explain offset direction, matrix shape and the difference between positional selection and numeric filtering.

The main diagonal belongs to the default retained region

After import numpy as np, define m = np.array([[3,5,7],[8,10,12],[13,15,17]]). The call np.triu(m) returns [[3,5,7],[0,10,12],[0,0,17]].

The main diagonal entries three, ten and seventeen remain, together with the entries above them. The lower-left positions become zero. No entries move upwards: every retained value stays at its original row and column coordinate.

Using zero-based indices, the default retained region contains positions whose column index is at least their row index. The first row therefore retains three entries, the second row retains two and the third row retains one in this square example.

NumPy upper triangular region

A positive offset excludes the main diagonal

The call np.triu(m,k=1) returns [[0,5,7],[0,0,12],[0,0,0]]. Its boundary is the first diagonal above the main diagonal. Only that boundary and the positions above it remain.

Positive k does not mean that more positions are always retained. For triu, moving the boundary upwards makes the retained upper region smaller. The original main diagonal becomes zero when k is one.

The output still has shape (3,3). Excluded positions are represented by zeros rather than removed from the array. That is why reading the result as a compact collection of three selected values would describe a different output structure.

A negative offset includes an additional lower diagonal

The call np.triu(m,k=-1) returns [[3,5,7],[8,10,12],[0,15,17]]. The boundary moves one diagonal below the main diagonal, so eight and fifteen are now retained. Only the lower-left entry thirteen is replaced with zero.

The general positional rule retains entries where column index minus row index is greater than or equal to k. This rule applies without comparing the actual numeric values. Negative entries in a retained position would remain negative, and positive entries outside the region would still become zero.

An output zero alone does not reveal whether the original entry was excluded. A retained entry might already have been zero. Keep the positional rule available when that distinction matters.

The result is a copy with the same shape

Triu returns a copy and preserves the input data type. Editing the result does not change the source matrix. The operation does not sort values, sum the region or produce only its coordinate list.

Rectangular matrices also work. For arrays with more than two dimensions, the triangular rule applies to the final two axes across the leading dimensions. Identify those matrix axes before explaining a layered array.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the offset, retained-position rule and output shape beside each upper triangular result.

NumPy tril preserves a lower triangular region and replaces entries above it with zero

Keeping a triangular region is different from collecting selected entries into a shorter vector. NumPy tril returns an array whose upper positions are replaced with zero while the lower region remains in place. Academia Master Trader presents this English lesson for readers in Chad, using constructed matrices to explain the diagonal boundary, offset direction and preserved output shape.

The default includes the main diagonal

After import numpy as np, define m = np.array([[2,4,6],[7,9,11],[12,14,16]]). The call np.tril(m) returns [[2,0,0],[7,9,0],[12,14,16]].

The main diagonal entries two, nine and sixteen remain. Entries below that diagonal also remain, while entries above it become zero. The operation follows positions rather than deciding which numeric values are larger or smaller.

Using zero-based indices, a position belongs to the default retained region when its column index is no greater than its row index. That positional rule explains why the first row keeps one entry, the second row keeps two and the third row keeps three.

NumPy lower triangular region

Negative offsets retain a smaller region

The call np.tril(m,k=-1) returns [[0,0,0],[7,0,0],[12,14,0]]. Its boundary lies one diagonal below the main diagonal. The original main diagonal is therefore replaced with zero along with the positions above it.

The call does not move entries down one row. Seven, twelve and fourteen stay in their original coordinates. The offset changes which positions are retained, not where values are placed in the output.

This distinction matters when a result contains many zeros. A zero can represent a position excluded by the triangular rule, or it can be an original value already present in a retained position. Looking only at output values cannot distinguish those cases.

Positive offsets retain an additional upper diagonal

The call np.tril(m,k=1) returns [[2,4,0],[7,9,11],[12,14,16]]. The first diagonal above the main diagonal is included. In this example, only the upper-right entry six is replaced with zero.

A positive k expands the retained region upwards, while a negative k narrows it downwards. The general retained-position rule is column index minus row index less than or equal to k. Stating this rule avoids relying on the visual appearance of a particular square matrix.

The retained entries keep their signs and magnitudes. Negative values are not excluded merely for being negative, and positive values above the boundary are still replaced with zero. Geometry, rather than a numeric threshold, determines the selection.

Shape and data storage remain separate questions

All three results keep shape (3,3) and the input data type. Tril returns a copy, so the result can be edited without changing the input matrix. It does not reduce the array to a list of lower entries or sum the triangular region.

Rectangular matrices also have lower triangular regions. For arrays with more than two dimensions, tril applies the rule to the final two axes, separately across the leading dimensions. Record those axes when explaining several matrix-shaped layers within one array.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the offset, positional rule and expected shape beside each triangular result.

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

The same function name can describe two related operations when the input has different dimensions. NumPy diag extracts entries from a two-dimensional array or places a one-dimensional array on a diagonal. Academia Master Trader presents this English lesson for readers in Somalia, using constructed arrays to explain dimensional roles, diagonal offsets and explicit copying for later edits.

A matrix input produces a diagonal vector

After import numpy as np, define m = np.array([[2,4,6],[7,9,11],[12,14,16]]). The call np.diag(m) returns [2,9,16]. These entries occupy positions where the row and column indices are equal.

The input has shape (3,3), but the extracted result has shape (3,). It contains the diagonal entries rather than their sum. Adding them would be a separate operation, and the function does not keep the other matrix entries in the returned vector.

The main diagonal runs from the upper left towards the lower right. It is not the opposite diagonal connecting the upper right to the lower left. Following row and column indices makes that distinction precise even when some values happen to be equal.

NumPy diagonal extraction

The k argument selects a parallel diagonal

The call np.diag(m,k=1) returns [4,11]. A positive offset selects a diagonal above the main diagonal. Here the selected column index is one greater than the row index.

The call np.diag(m,k=-1) returns [7,14]. A negative offset selects a diagonal below the main diagonal. The selected row index is one greater than the column index in this example.

The output length can change with the offset because a parallel diagonal can contain fewer entries. An offset describes a diagonal's position, not the number of entries to collect. Rectangular matrices can also have diagonals with lengths determined by their available rows and columns.

A vector input constructs a two-dimensional matrix

Define v = np.array([3,5,8]). The call np.diag(v) returns [[3,0,0],[0,5,0],[0,0,8]], with shape (3,3). The vector supplies the main diagonal, and the remaining positions are zero.

The call np.diag(v,k=1) constructs [[0,3,0,0],[0,0,5,0],[0,0,0,8],[0,0,0,0]], with shape (4,4). The extra space allows all three supplied entries to fit on the diagonal above the main diagonal.

Input dimensionality therefore determines whether diag selects existing entries or constructs a matrix. Read that dimensionality before interpreting the result; a vector and a single-row matrix are different inputs.

Constructing a diagonal matrix from an extracted diagonal does not recover the full original matrix. The selected entries return to their diagonal positions, but the other positions become zero. Information outside the selected diagonal was not preserved by the extraction step.

Separate extraction from editing and summation

Do not assume that assigning into an extracted diagonal will update the source matrix. Copy and view behaviour can depend on the NumPy version and extraction route. Use np.diag(m).copy() when an independent, editable diagonal vector is needed.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input dimensionality, offset and output shape before explaining a diagonal operation.

NumPy tile repeats whole array patterns according to repetition counts for each axis

Repeated patterns can be assembled by copying an entire array rather than repeating each individual entry together. NumPy tile constructs such patterns using repetition counts. Academia Master Trader presents this English lesson for readers in Comoros, using constructed arrays to explain block order, axis counts and the extra dimensions introduced when repetition counts require them.

A vector repeats as a complete pattern

After import numpy as np, define v = np.array([2,5,8]). The call np.tile(v,2) returns [2,5,8,2,5,8]. The complete three-entry pattern appears twice in sequence.

This differs from repeating each entry next to itself. The call np.repeat(v,2) returns [2,2,5,5,8,8]. Both results contain six entries, but their order expresses a different operation. Read the intended pattern before choosing between tile and repeat.

The repetition count is not the desired final length. A count of two means two copies of the input pattern along the relevant axis. For this vector, multiplying its length three by that count gives an output length of six.

NumPy tiled vector

Several repetition counts can add a leading dimension

The call np.tile(v,(2,3)) returns a matrix with shape (2,9). Its two rows are both [2,5,8,2,5,8,2,5,8].

The vector starts with shape (3,). Because the repetition tuple contains two counts, NumPy treats the input as shape (1,3) before applying them. The first count repeats that row twice, and the second repeats its three-entry pattern three times across columns.

This alignment comes from the leading dimension added to the vector. It does not mean that every repetition count applies directly to an axis already present in the original input. Write the promoted shape beside the repetition tuple when explaining the resulting dimensions.

Short repetition tuples align with the final axes

Define m = np.array([[1,2],[3,4]]). The call np.tile(m,2) returns [[1,2,1,2],[3,4,3,4]], with shape (2,4).

The single count is treated as (1,2) for this two-dimensional input. The matrix does not double in both directions. Its row count stays two, while its column count doubles to four.

The call np.tile(m,(2,1)) instead returns [[1,2],[3,4],[1,2],[3,4]], with shape (4,2). The two-row block repeats vertically, while each row retains its original width. Compare the block boundaries as well as the final dimensions.

The order inside each copied block remains the input order. Tile does not sort the pattern or interpolate values between copies. A repeated boundary therefore joins the final entry of one copy directly to the first entry of the next.

Repetition is separate from arithmetic broadcasting

Tile constructs a repeated output array. If the goal is only to combine a smaller array with a larger one through compatible arithmetic, broadcasting may express that calculation without explicitly building all repeated copies.

Choose tile when the repeated arrangement itself is needed. Keep the input shape, repetition tuple and expected output shape together so another reader can reconstruct the pattern without guessing how the counts align.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Describe whether the task repeats whole patterns or individual entries before choosing an array operation.

NumPy rot90 rearranges array entries through quarter turns in a selected plane

A quarter turn changes how array positions line up across two axes. NumPy rot90 performs these turns without calculating new values between the original entries. Academia Master Trader presents this English lesson for readers in Djibouti, using constructed arrays to explain rotation direction, output shape and the two axes defining a rotation plane.

The default rotates a matrix counterclockwise

After import numpy as np, define m = np.array([[1,2,3],[4,5,6]]). The call np.rot90(m) returns [[3,6],[2,5],[1,4]]. With the default axis order and one quarter turn, the matrix rotates counterclockwise.

The original top row becomes the first column, read from bottom to top. The final input column becomes the first output row. Following a distinctive entry, such as one or six, makes this positional movement easier to explain than relying on shape alone.

The input shape is (2,3), while the output shape is (3,2). A quarter turn exchanges the lengths of the two selected axes. No entries are added, removed or averaged during that rearrangement.

NumPy quarter turn

The k argument counts quarter turns

The call np.rot90(m,k=2) returns [[6,5,4],[3,2,1]]. Two quarter turns make a half turn, leaving this matrix with its original shape (2,3) but a different arrangement.

The call np.rot90(m,k=-1) returns [[4,1],[5,2],[6,3]]. Under the default axes, a negative quarter turn rotates clockwise. Four quarter turns return the original ordering, so k equal to four produces the same arrangement as k equal to zero.

Keep direction attached to the axis order. Saying that positive k always means counterclockwise is incomplete for a general array, because changing the order of the selected axes changes the direction represented by the same k.

The axis pair defines the plane and its direction

The default pair is (0,1). The call np.rot90(m,k=1,axes=(1,0)) returns [[4,1],[5,2],[6,3]], matching a negative quarter turn with the default pair.

For an array with more than two dimensions, choose the two distinct axes that define the intended plane. The remaining axes are not exchanged by that rotation. Naming both axes is useful when separate layers or channels must retain their role while another pair of dimensions rotates.

This operation is a positional rearrangement on a grid. It does not rotate a picture through an arbitrary angle or estimate intermediate pixel values. Quarter turns fit the existing grid, which is why every output entry can be traced directly to an input entry.

A rotated view can share data with the source

Rot90 accepts arrays with at least two dimensions. A one-dimensional vector does not provide the required two-axis plane. Check the dimensional structure before choosing an axis pair.

For an existing NumPy array, the returned result is a rotated view. It can share its underlying data with the source, so later edits through the view can affect the original array. Use np.rot90(m).copy() when the rotated result needs independent storage.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record k, the ordered axis pair and the expected output shape before interpreting a quarter turn.

NumPy flip reverses entry order along selected axes while preserving array shape

Reversing an array changes positional order rather than numeric values. NumPy flip reverses entries along one or more selected axes, keeping the original shape. Academia Master Trader presents this English lesson for readers in Mauritania, using constructed arrays to explain row and column reversal, the default axis choice and the shared memory of a returned view.

Reversing a vector changes its positional order

After import numpy as np, define v = np.array([7,2,9,4]). The call np.flip(v) returns [4,9,2,7]. The final entry becomes the first, the next-to-final entry becomes the second and the same reversal continues through the sequence.

This is not sorting. The result is neither ascending nor descending because flip follows the original positions rather than comparing values. It also differs from a circular shift, which moves entries by a fixed offset and wraps them across a boundary.

The output still has four entries. Reversing the same axis twice restores the original order. The operation therefore changes arrangement without adding entries or reducing the sequence to a summary.

NumPy axis reversal

The selected axis determines which positions reverse

Define m = np.array([[1,2,3],[4,5,6]]). The call np.flip(m,axis=0) returns [[4,5,6],[1,2,3]]. Row positions reverse, but the order of entries within each row remains unchanged.

The call np.flip(m,axis=1) returns [[3,2,1],[6,5,4]]. Column positions reverse within each row, while the rows retain their original vertical order. Both outputs have shape (2,3).

A negative axis counts backwards from the final axis. For this two-dimensional matrix, axis negative one identifies the column axis, so np.flip(m,axis=-1) gives the same result as axis one. Stating the axis avoids confusing row reversal with column reversal.

Shape alone cannot identify a reversal. The matrix still has two rows and three columns after either operation, even though its entries occupy different positions. Compare coordinates and values alongside shape when explaining how a reversed result relates to its source.

Omitting axis reverses every axis

The call np.flip(m) returns [[6,5,4],[3,2,1]]. Both row and column positions reverse. Supplying the tuple explicitly, as np.flip(m,axis=(0,1)), produces the same arrangement for this matrix.

This default does not mean that only the final axis is reversed. It applies to all axes of the input. The distinction becomes especially useful with arrays containing more than two dimensions, where several positional directions can be reversed together.

The returned view can share changes with its source

For an existing NumPy array, flip returns a view rather than an independent copy. The reordered view still refers to the underlying array data. Assigning through that view can therefore change an entry in the source array.

When an independent result is needed, use np.flip(m,axis=1).copy(). The copy separates later edits to the result from the original array. Keep reversal and copying as distinct decisions: one controls order, while the other controls whether data storage is shared.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the axes and whether the result is a view before explaining or editing a reversed array.

NumPy roll moves array entries with wraparound rather than inserting empty positions

Moving entries along an array can mean different things at its boundaries. NumPy roll uses circular movement: entries crossing one end return at the other end. Academia Master Trader presents this English lesson for readers in Tunisia, using constructed arrays to explain signed shifts, axis selection and flattened movement that restores the original shape.

A positive shift moves entries towards higher positions

After import numpy as np, define v = np.array([10,20,30,40]). The call np.roll(v,1) returns [40,10,20,30]. The final entry moves to the first position, while the other entries move one position to the right.

The call np.roll(v,-1) returns [20,30,40,10]. A negative shift moves entries towards lower positions, with the first entry wrapping to the end. No input entry disappears and no empty placeholder is inserted.

A shift of four positions returns the original ordering for this four-entry vector. A shift of five has the same ordering as a shift of one. Circular movement repeats after a full circuit of the selected axis.

NumPy circular movement

Choosing an axis determines the boundary that wraps

Define m = np.array([[1,2,3],[4,5,6]]). The call np.roll(m,1,axis=1) returns [[3,1,2],[6,4,5]]. Each row moves across its columns, and the final column wraps to the first column.

The call np.roll(m,1,axis=0) returns [[4,5,6],[1,2,3]]. Entire rows change positions because movement follows the row axis. The entries within each row retain their order.

Both outputs have shape (2,3), matching the input. An axis selects where positions move, not a dimension to remove. Keep the shift and axis together when describing a result, because the same shift can rearrange very different groups of entries.

Omitting the axis uses one flattened sequence

The call np.roll(m,1) returns [[6,1,2],[3,4,5]]. NumPy first treats the matrix as the sequence [1,2,3,4,5,6], rolls that sequence and then restores the original shape.

The entry three therefore crosses the boundary between the first and second output rows. This differs from rolling each row independently. Although the output remains a matrix, omitting axis does not preserve the input rows as separate circular sequences.

Several axes can move in one call

The call np.roll(m,(1,-1),axis=(0,1)) returns [[5,6,4],[2,3,1]]. The first shift applies to axis zero, and the second applies to axis one. Pair each shift with the axis in the corresponding tuple position.

Roll rearranges positions rather than calculating new numeric values. It does not sort entries, reverse their order or add padding. The original array remains available beside the returned result, so the positional changes can be explained directly from the two arrays.

Do not confuse a circular shift with delaying a sequence using a blank starting value. In a delay with padding, a boundary position would need a replacement value. Roll instead supplies an existing entry from the opposite end, which is a different boundary assumption.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shift, axis and boundary rule before interpreting a circular rearrangement.

NumPy cumprod keeps the intermediate products along a chosen array axis

Multiplying an entire sequence gives one final product. NumPy cumprod instead records a product at every position, preserving the stages of multiplication. Academia Master Trader presents this English lesson for readers in Morocco, using constructed arrays to explain cumulative products, independent axis sequences and the effect of a zero within a sequence.

Each output multiplies the current entry by the preceding product

After import numpy as np, define v = np.array([2,3,-1,4]). The call np.cumprod(v) returns [2,6,-6,-24]. The first output is two. Multiplying by three gives six, multiplying by negative one gives negative six and multiplying by four gives negative twenty-four.

The vector retains four positions. Each result includes all entries up to and including that position. The output is therefore different from a reduction that keeps only the final product.

Cumulative products need not grow or remain positive. A negative factor can change the sign, while a factor between zero and one can reduce the magnitude. The operation follows multiplication rather than imposing a direction on the results.

NumPy cumulative products

Specifying an axis creates independent accumulation sequences

Define m = np.array([[2,3,4],[5,2,3]]). The call np.cumprod(m,axis=1) returns [[2,6,24],[5,10,30]], with shape (2,3). Each row starts its own sequence and accumulates across its columns.

The call np.cumprod(m,axis=0) returns [[2,3,4],[10,6,12]]. Each column is accumulated down the rows. The first row provides the initial products, while the second row multiplies corresponding entries from both input rows.

Both results preserve the matrix shape. The chosen axis identifies the direction of accumulation, not an axis to discard. Naming the axis alongside an example helps readers distinguish the separate sequences within the same matrix.

Without an axis the matrix becomes one sequence

The call np.cumprod(m) returns [2,6,24,120,240,720], with shape (6,). Its accumulation order follows the flattened sequence [2,3,4,5,2,3].

The fourth result is one hundred and twenty because the product from the first row continues into the second row. It does not restart at five. Omitting axis therefore changes the output shape and the membership of each cumulative product.

Keep the original order visible when explaining the calculation. Reordering factors preserves the final exact product in ordinary arithmetic, but changes the intermediate products associated with individual positions. A cumulative result describes the supplied sequence, rather than an unordered collection of values.

A zero affects every later product in its sequence

For z = np.array([2,3,0,4]), np.cumprod(z) returns [2,6,0,0]. Once zero enters this finite integer sequence, multiplying subsequent entries keeps the running product at zero. Cumprod does not automatically restart after the zero.

The optional dtype argument controls the accumulator and output type. For example, np.cumprod(v,dtype=np.float64) returns [2.0,6.0,-6.0,-24.0]. Integer multiplication can overflow without raising an error, so choose a type suited to the intended numeric range. By default, the operation returns a new array and leaves the input available for comparison.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the axis, expected shape and numeric type before explaining the intermediate products.

NumPy cumsum records a running total at every position along an array axis

A final sum describes a whole sequence, while cumulative sums retain the intermediate totals. NumPy cumsum adds entries progressively along a chosen axis. Academia Master Trader presents this English lesson for readers in Algeria, using constructed arrays to explain running totals, axis direction and the shape produced when no axis is supplied.

Every output includes the current entry and those before it

After import numpy as np, define v = np.array([3,5,-2,8]). The call np.cumsum(v) returns [3,8,6,14]. The first total is three. Adding five gives eight, adding negative two gives six and adding eight gives fourteen.

The third total is lower than the second because the next entry is negative. Cumulative does not mean that every total must increase. It means that the calculation includes progressively more entries from the same ordered sequence.

The output has four entries, matching the vector's length. Each result belongs to the corresponding input position. A simple sum would return fourteen alone, losing the intermediate totals that cumsum preserves.

NumPy running totals

An axis defines which sequence is accumulated

Define m = np.array([[2,4,7],[3,6,8]]). The call np.cumsum(m,axis=1) returns [[2,6,13],[3,9,17]], with shape (2,3). Each row has its own running total across columns.

The call np.cumsum(m,axis=0) returns [[2,4,7],[5,10,15]]. Here each column has its own running total down the rows. The first row stays unchanged, and the second row combines corresponding entries from both input rows.

Both operations preserve this matrix's shape because an axis was supplied. They do not reduce that axis to a single final total. Keep the axis next to the result when explaining which entries contributed to an intermediate sum.

Omitting the axis accumulates a flattened sequence

The call np.cumsum(m) returns [2,6,13,16,22,30], with shape (6,). The input is treated as the sequence [2,4,7,3,6,8]. Accumulation continues from the final entry of the first row into the first entry of the second row.

This differs from separately accumulating each row. The fourth total is sixteen rather than three because it includes the thirteen already accumulated from the first row. Omitting axis therefore changes both the output layout and the sequence of additions.

By default, cumsum returns a new result rather than replacing the input. This lets the original entries remain available beside the running totals. Preserving that pair is useful when explaining why a particular total changed from the previous position.

The accumulator dtype affects numeric behaviour

The optional dtype argument controls the accumulator and returned array type. For example, np.cumsum(v,dtype=np.float64) returns [3.0,8.0,6.0,14.0]. Choose a numeric type that fits the intended range and precision.

Integer arithmetic can overflow without raising an error. Floating point arithmetic can also accumulate rounding differences, so the final cumulative total need not exactly equal a separate sum computed through another summation routine. These are numeric representation issues rather than changes to the positional meaning of cumsum.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the accumulation axis, expected shape and numeric type beside each running total.

NumPy diff subtracts adjacent entries along a selected array axis

An ordered sequence can be described through the changes between neighbouring entries. NumPy diff calculates discrete differences along an array axis. Academia Master Trader presents this English lesson for readers in Sudan, using constructed arrays to explain subtraction order, shorter output dimensions and the distinction between a second difference and a wider gap.

The next entry minus the current entry defines a first difference

After import numpy as np, define v = np.array([2,6,13,23]). The call np.diff(v) returns [4,7,10]. These values come from six minus two, thirteen minus six and twenty three minus thirteen.

Each output position describes one neighbouring pair. Four input entries provide three such pairs, so the result has shape (3,). Diff does not compare every entry with the first one. It also does not retain the first input value as an initial output entry.

A decreasing step produces a negative difference for a signed numeric array. For example, np.diff(np.array([9,4,7])) returns [-5,3]. The order of subtraction matters: each later entry is reduced by the entry immediately before it.

NumPy adjacent differences

Higher differences repeat the operation on the previous result

The call np.diff(v,n=2) returns [3,3]. First NumPy obtains [4,7,10], then it takes adjacent differences of that intermediate result. Seven minus four and ten minus seven both equal three.

Setting n to two does not mean comparing entries two positions apart in the original vector. A higher difference is a repeated operation. Writing the intermediate result makes this distinction visible and explains why the selected output dimension becomes shorter again.

With n=0, NumPy returns the input as it is. For ordinary positive orders within the available axis length, each round removes one position along that axis when no extra entries are supplied.

The axis determines which entries are neighbours

Define m = np.array([[2,6,13],[5,12,20]]). The call np.diff(m,axis=1) returns [[4,7],[7,8]], with shape (2,2). Subtraction occurs across columns within each row.

The call np.diff(m,axis=0) returns [[3,6,7]], with shape (1,3). It subtracts the first row from the second, matching corresponding columns. For this matrix, omitting axis uses the final axis, so it agrees with axis one.

Prepended values create an additional neighbouring pair

The call np.diff(v,prepend=0) returns [2,4,7,10]. NumPy places zero before the original sequence before calculating differences. The first output is therefore two minus zero, not a copied value added after the calculation.

Choose that additional value for a stated reason rather than using it only to force a desired output length. It changes the sequence being compared and therefore changes the meaning of the first difference.

Array dtype also matters. Unsigned integers cannot represent ordinary negative results, so a decreasing step can wrap within that dtype. Convert to a suitable signed type before differencing when negative changes are intended. Boolean inputs instead report whether neighbouring values differ, rather than producing signed numeric changes.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the axis, difference order and any added endpoint before interpreting the output.