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 at least 2d supplies a minimum dimensionality rather than a fixed matrix shape

An input can arrive as a scalar, a vector or an array with several axes. NumPy at least 2d provides a convenient way to give inputs a minimum of two dimensions. Academia Master Trader presents this English lesson for readers in Benin, using constructed examples to explain row-shaped vectors, preserved higher-dimensional arrays and copy behavior.

A scalar and a vector receive different shapes

After import numpy as np, the call np.atleast_2d(8) returns an array displaying [[8]], with shape (1,1). One value now occupies a two-dimensional arrangement with one row and one column.

For x = np.array([2,5,8]), the call np.atleast_2d(x) returns [[2,5,8]], with shape (1,3). A one-dimensional input becomes a row-shaped array, not a column-shaped array.

The three values remain in their original order. The operation adds structural dimensions where needed; it does not calculate new values or repeat the entries to fill a larger table.

If a later step requires shape (3,1), the row-shaped result is not interchangeable with that column shape. Choose an explicit shape operation that expresses the required orientation rather than assuming that any two-dimensional result will fit.

NumPy at least 2d input and output shapes

At least two does not mean exactly two

An existing two-dimensional array keeps its shape. For matrix = np.array([[1,2],[3,4]]), the call np.atleast_2d(matrix) still has shape (2,2).

A three-dimensional array is also preserved. For cube = np.zeros((2,3,4)), the call np.atleast_2d(cube) keeps shape (2,3,4). It does not flatten that array into a matrix.

The name describes a lower bound on the number of dimensions, not a guarantee of exactly two axes. This distinction matters when a later operation accepts only matrices rather than arbitrary arrays.

Check the output shape against that later operation's actual requirements. A minimum-dimensionality helper cannot by itself establish every part of an input contract.

Several inputs are handled separately

The call a,b = np.atleast_2d(8,[2,5,8]) returns separate arrays with shapes (1,1) and (1,3). It does not stack them into one rectangular object or force their shapes to match.

Non-array inputs are converted to arrays. Existing arrays with enough dimensions are preserved, and NumPy avoids copies where possible.

Use this helper when each input needs the same minimum dimensionality rule. Use a different operation when the actual goal is joining inputs, matching their sizes or reducing their number of axes.

Shape normalization is not independent storage

Do not assume that the returned array has separate editable data merely because its shape is different. A view can share the source array's storage.

When independent editing is required, take an explicit copy, such as independent = np.atleast_2d(x).copy(). Keep the storage decision separate from the dimensionality decision.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, output shape and required orientation before using minimum-dimensionality helpers.

NumPy expand dims adds length-one axes while keeping the original entries

A vector can represent one row, one column or data awaiting an extra grouping direction. NumPy expand dims adds explicit length-one axes so these structural choices appear in the shape. Academia Master Trader presents this English lesson for readers in Equatorial Guinea, using small constructed arrays to separate axis insertion from value repetition.

One vector can acquire different orientations

After import numpy as np, define x = np.array([3,6,9]). Its shape is (3,), which describes one axis containing three positions. A one-dimensional vector has no separate row and column axes.

The call row = np.expand_dims(x,axis=0) gives shape (1,3) and displays [[3,6,9]]. The new first axis has length one. The existing length-three axis moves to position one.

The call column = np.expand_dims(x,axis=1) gives shape (3,1) and displays [[3],[6],[9]]. This time the new singleton axis follows the existing axis. The same three values now have a column-shaped arrangement.

Neither operation adds numerical entries. Both results contain three elements, even though their shapes have two components rather than one.

NumPy expand dims row and column shapes

Axis positions describe the expanded shape

The axis argument identifies where a new axis appears in the output shape. For this vector, axis zero inserts before its current axis, while axis one inserts after it.

A negative axis can express a position counted from the end. The call np.expand_dims(x,axis=-1) produces shape (3,1), matching the column-shaped result above.

Keep axis positions distinct from axis lengths. Inserting at axis zero creates a dimension of length one; it does not create a dimension of length zero or remove the first value.

For several new axes, pass a tuple. The call np.expand_dims(x,axis=(0,2)) produces shape (1,3,1). The singleton axes occupy positions zero and two in the expanded result, with the original length-three axis between them.

Extra axes are not repeated data

Adding a singleton direction can make an array's intended alignment explicit before broadcasting. Expansion itself does not fill that direction with repeated copies, and it does not calculate a sum or average.

Before combining arrays, write their shapes in order. A row-shaped (1,3) array and a column-shaped (3,1) array align differently, even when their flattened values match.

This distinction matters when later expressions use shape compatibility. An extra axis is a structural instruction for alignment, not evidence that more observations have been collected.

The result is a view

NumPy documents the returned result as a view of the input with more dimensions. Do not assume that inserting an axis allocates independent editable values.

For separate data storage, use an explicit copy, such as separate = np.expand_dims(x,axis=0).copy(). Removing a known length-one axis with squeeze can reverse the corresponding shape change, but does not itself promise a copy either.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the original shape, insertion positions and resulting shape before relying on an expanded array.

NumPy squeeze removes length-one axes without discarding array entries

A dimension with length one can describe a row, a column or an extra grouping direction. NumPy squeeze removes such dimensions from an array's shape. Academia Master Trader presents this English lesson for readers in Gabon, using constructed arrays to explain selective axis removal, output dimensionality and shared data storage.

A singleton dimension contains one position

After import numpy as np, define x = np.array([[[2],[4],[6]]]). The input has shape (1,3,1): its first and final axes have length one, while its middle axis has length three.

The call np.squeeze(x) returns an array displaying [2,4,6], with shape (3,). Both length-one axes have been removed from the shape. The three stored entries remain present and in the same order.

Squeeze does not remove entries whose numeric value happens to be one. Its rule concerns axis lengths, not data values. A length-three axis remains length three even if all its entries contain the number one.

NumPy squeeze shape change

Selecting an axis preserves other singleton directions

The call np.squeeze(x,axis=0) produces shape (3,1). It removes only the first axis, leaving the final singleton axis in place.

The call np.squeeze(x,axis=2) produces shape (1,3). It removes only the final axis, leaving the first singleton axis in place. These two results contain the same three entries but have different row and column interpretations.

The call np.squeeze(x,axis=(0,2)) produces shape (3,), matching the default result for this particular input. Listing axes explicitly makes the intended structural change clear.

Axis numbers refer to the input shape. Keep that shape beside the call so the selected axes can be interpreted without guessing from the printed values.

A longer axis cannot be squeezed away

The call np.squeeze(x,axis=1) raises ValueError because axis one has length three. Squeeze does not combine those three entries, choose one of them or discard them to satisfy the request.

This restriction distinguishes axis removal from aggregation or indexing. A sum could combine values, and indexing could select a position, but neither operation has the same meaning as removing a singleton direction.

When a later calculation expects a row or a column, removing every singleton axis may remove useful structure. Select only the axes whose absence matches the intended output contract.

Removing every axis leaves a zero-dimensional array

For single = np.array([[7]]), the call np.squeeze(single) returns a zero-dimensional array with shape (). It is not a length-one vector, and squeeze does not turn it into a Python scalar.

Squeeze returns the input itself or a view into it, rather than promising independent copied data. If later editing must not affect the source, make an explicit copy after squeezing.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, chosen axes and expected output shape before removing singleton dimensions.

NumPy broadcast to presents repeated values through a read-only view

A repeated-looking array does not always require repeated stored data. NumPy provides a broadcasting function that presents an existing array at a compatible target shape. Academia Master Trader presents this English lesson for readers in Cameroon, using constructed arrays to explain shape compatibility, repeated coordinates and the difference between a view and an independent copy.

A vector can appear across several rows

After import numpy as np, define x = np.array([3,6,9]). The call np.broadcast_to(x,(2,3)) returns a view whose displayed values are [[3,6,9],[3,6,9]].

The input has shape (3,), while the requested output has shape (2,3). For shape comparison, the missing leading dimension behaves as one. That singleton direction can expand to two rows while the existing length-three direction remains unchanged.

The result does not mean that each displayed value has its own separate storage location. More than one output position can refer to the same underlying input value. This matters when deciding whether the result can be edited independently.

NumPy broadcasting view

Compatibility is checked from the trailing dimensions

Broadcasting compares dimensions from the right. Matching dimensions are compatible, and a dimension of size one can expand to the corresponding target size. Missing leading dimensions are treated as ones for this comparison.

The target (2,3) works for x because the trailing length three matches. A target of (2,4) does not work: the existing length-three dimension cannot expand to four. An incompatible target raises ValueError rather than cycling through values to fill the requested shape.

Broadcasting is therefore not a general resizing instruction. It follows shape rules and does not interpolate, wrap values around a row or choose a new ordering for them.

A column-shaped input repeats in the other direction

Define column = np.array([[4],[8]]), which has shape (2,1). The call np.broadcast_to(column,(2,3)) displays [[4,4,4],[8,8,8]].

Here the first dimension already matches two rows. The second dimension expands from one column to three. The same target shape can therefore show different patterns depending on the input shape.

Keep a vector of shape (3,) distinct from a column of shape (3,1). Their axes differ, so their compatible targets and repetition directions need not match.

Copy the view when independent editing is needed

The returned broadcast view is read-only and typically not contiguous. Do not assume it owns a separate block of repeated values simply because its printed display resembles a filled matrix.

Use expanded = np.broadcast_to(x,(2,3)).copy() to create an independent, editable array. Assigning expanded[0,0] = 99 then changes that copy without changing x or the second row's first entry.

A view is useful when the repeated representation is needed only for reading or as input to an expression. A copy is a separate choice when later work requires independent writable entries.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, target shape, compatibility rule and copying decision beside every broadcast representation.

NumPy meshgrid expands coordinate vectors with an explicit indexing convention

Coordinate vectors can describe the locations along separate directions of a grid. NumPy meshgrid combines them into coordinate arrays suitable for expressions evaluated at many points. Academia Master Trader presents this English lesson for readers in the Central African Republic, using constructed coordinates to explain output shape, indexing conventions and sparse representations.

Two coordinate vectors describe six points

After import numpy as np, define x = np.array([2,4,6]) and y = np.array([10,20]). The assignment X,Y = np.meshgrid(x,y) uses the default indexing convention, xy.

X is [[2,4,6],[2,4,6]], while Y is [[10,10,10],[20,20,20]]. Both arrays have shape (2,3). At a particular row and column, their entries jointly describe one coordinate pair.

For example, position (1,2) represents x equal to six and y equal to twenty. The arrays contain coordinate components, not a list of paired input elements. Meshgrid forms every combination of the supplied x and y coordinates.

NumPy meshgrid coordinate arrays

Default xy indexing places y along rows

With xy indexing, the first output dimension has the length of y, and the second has the length of x. That explains why three x coordinates and two y coordinates produce arrays with two rows and three columns.

X varies across each row, while Y varies down the rows. This convention is useful when relating arrays to Cartesian plotting coordinates, but the chosen convention should always be stated rather than inferred from variable names.

The expression X + Y returns [[12,14,16],[22,24,26]]. Every entry adds the two coordinate components at the same grid position. This is an illustrative function of coordinates, not a rule for combining arbitrary datasets.

Matrix indexing follows the input vector order

The assignment A,B = np.meshgrid(x,y,indexing='ij') returns arrays with shape (3,2). A is [[2,2],[4,4],[6,6]], while B is [[10,20],[10,20],[10,20]].

The coordinate combinations are the same, but their arrangement in array axes differs. With ij indexing, the first input vector varies along the first axis and the second varies along the second axis.

Changing the convention is therefore more than changing a label. Code that indexes or labels the result must use the same axis interpretation as the grid construction.

Sparse coordinates still support a full result

The assignment xs,ys = np.meshgrid(x,y,sparse=True) retains default xy indexing. The shapes are (1,3) for xs and (2,1) for ys. The expression xs + ys broadcasts to the same (2,3) result as X plus Y.

Sparse coordinate arrays keep repeated coordinates implicit. They are not compressed sparse matrices, and an expression involving both directions can still create a complete result array.

Meshgrid copies coordinate data by default. If copy=False is requested, returned arrays may share storage and have repeated references to one memory location. Make copies before writing when independent editable arrays are needed.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record vector lengths, indexing convention and output shapes before interpreting a coordinate grid.

NumPy indices builds coordinate grids whose leading axis identifies each dimension

An array's values and its coordinates answer different questions. NumPy indices constructs coordinate arrays for a requested grid shape. Academia Master Trader presents this English lesson for readers in the Republic of the Congo, using a small rectangular grid to explain row coordinates, column coordinates, dense output and sparse coordinate representations.

A two-dimensional grid needs two coordinate arrays

After import numpy as np, define grid = np.indices((2,3)). The requested grid has two rows and three columns. The returned dense array has shape (2,2,3).

The extra leading dimension has length two because there are two coordinate directions. grid[0] contains row indices: [[0,0,0],[1,1,1]]. grid[1] contains column indices: [[0,1,2],[0,1,2]].

The row coordinate stays constant across each row and changes when moving downwards. The column coordinate changes when moving across a row and repeats in the next row. These are positions, not measurements stored in a separate dataset.

NumPy indices coordinate grids

The leading axis identifies the coordinate direction

At row one, column two, grid[0,1,2] is one and grid[1,1,2] is two. Together they describe the coordinate pair (1,2).

Do not interpret the leading axis as another spatial dimension of the requested rectangle. It selects which coordinate component is being read. The requested grid remains two-dimensional even though the dense result is a three-dimensional array.

More generally, a requested shape with N dimensions produces dense output whose shape begins with N, followed by the requested dimensions. Each subarray supplies coordinates along one corresponding axis.

Sparse output keeps repeated coordinates implicit

The assignment rows, cols = np.indices((2,3),sparse=True) returns a tuple of coordinate arrays. Here rows is [[0],[1]] with shape (2,1), while cols is [[0,1,2]] with shape (1,3).

These are ordinary arrays with singleton dimensions, not a compressed sparse matrix format. Their shapes allow broadcasting to combine the coordinate directions without first storing both complete dense grids.

For example, 10*rows + cols produces [[0,1,2],[10,11,12]]. The result has shape (2,3) because broadcasting combines the two coordinate directions. The expression is a constructed coordinate label, not a formula for interpreting every dataset.

Coordinate grids can describe a positional condition

The expression rows == cols produces [[True,False,False],[False,True,False]]. It identifies matching row and column indices within the rectangle.

This condition depends only on coordinates. It does not inspect numeric values from an existing matrix. To use a coordinate condition with data, first establish that the data shape and the grid shape refer to the same axes.

Indices accepts dtype to choose the coordinate array data type. Keep that storage choice separate from the requested grid dimensions and the meaning assigned to each coordinate direction.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the requested shape, dense or sparse representation and coordinate-axis order before using a grid in another expression.

NumPy tri fills a lower triangular region with ones while preserving the requested rectangle

A triangular pattern can describe which positions belong to a lower region of a matrix. NumPy tri constructs that pattern using ones and zeros. Academia Master Trader presents this English lesson for readers in the Democratic Republic of the Congo, using small constructed arrays to explain dimensions, diagonal offsets and the difference between creating a pattern and selecting existing values.

The default region includes the main diagonal

After import numpy as np, the call np.tri(3,dtype=int) returns [[1,0,0],[1,1,0],[1,1,1]]. The first argument sets the number of rows. Because no column count is supplied, the result is square with shape (3,3).

Ones appear on the main diagonal and below it. Zeros appear above the main diagonal. The first row contains one one, the second row contains two and the third row contains three.

These entries are created from a positional rule. Tri does not read another matrix and preserve its lower entries. It constructs a new array whose values describe membership in the selected region.

NumPy tri lower region

A second size argument sets the column count

The call np.tri(3,4,dtype=int) returns [[1,0,0,0],[1,1,0,0],[1,1,1,0]]. Its shape is (3,4): three rows and four columns.

The rectangular boundary and the diagonal boundary are different constraints. The fourth column exists, but none of its positions falls inside this particular lower region. It therefore contains zeros throughout.

Reversing the sizes would create four rows and three columns instead. Write the intended row and column counts before reasoning about which positions contain ones.

A positive offset expands the region upwards

The call np.tri(3,4,k=1,dtype=int) returns [[1,1,0,0],[1,1,1,0],[1,1,1,1]]. The boundary moves to the diagonal immediately above the main diagonal, and the region at and below it is filled with ones.

The call np.tri(3,4,k=-1,dtype=int) returns [[0,0,0,0],[1,0,0,0],[1,1,0,0]]. Here the boundary lies one diagonal below the main diagonal, so the main diagonal itself contains zeros.

Both calls retain shape (3,4). The offset changes the filled region, not the array dimensions. No values wrap around an edge, and a row can contain no ones when the boundary begins below it.

Coordinates state the rule precisely

With zero-based indices, position (i,j) contains one when j <= i+k; otherwise it contains zero. This condition works for rectangular arrays as well as square ones.

The examples request dtype=int for integer entries. The documented default is floating point, and dtype=bool can represent the same region with true and false entries. Changing the data type does not change the boundary coordinates.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the shape, offset and coordinate condition beside every triangular pattern so its meaning remains clear.

NumPy eye creates a matrix with ones on one diagonal and zeros elsewhere

A diagonal pattern can be constructed directly, without editing individual cells. NumPy eye creates a two-dimensional array with ones on a chosen diagonal and zeros in the remaining positions. Academia Master Trader presents this English lesson for readers in Burundi, using constructed matrices to explain row counts, column counts, offsets and data types.

One size produces a square matrix

After import numpy as np, the call np.eye(3,dtype=int) returns [[1,0,0],[0,1,0],[0,0,1]]. It creates three rows and, because no separate column count is supplied, three columns.

The main diagonal contains positions whose row and column indices match. Every other position contains zero. This square, main-diagonal pattern is an identity matrix. The output has shape (3,3).

Eye constructs a new pattern from size and diagonal parameters. It does not extract entries from an existing matrix or inspect a supplied collection of values. To build a diagonal from specific numbers rather than ones, another construction is needed.

NumPy eye rectangular pattern

A separate column count allows a rectangular result

The call np.eye(3,4,dtype=int) returns [[1,0,0,0],[0,1,0,0],[0,0,1,0]]. The first argument is the row count, and the second is the column count. The shape is therefore (3,4).

The fourth column does not gain a one merely because it exists. Only positions on the selected diagonal receive ones. A rectangular output is a diagonal pattern, but it is not a square identity matrix.

Write the intended shape before describing the resulting entries. Reversing the two size arguments creates a different rectangular array, even though both calls still place ones on their main diagonals.

The offset moves the diagonal, not the array boundary

The call np.eye(3,4,k=1,dtype=int) returns [[0,1,0,0],[0,0,1,0],[0,0,0,1]]. Positive k selects an upper diagonal. Here the ones start in column one of row zero.

The call np.eye(3,4,k=-1,dtype=int) returns [[0,0,0,0],[1,0,0,0],[0,1,0,0]]. Negative k selects a lower diagonal. The first row contains no one because that diagonal begins below it.

Both outputs retain shape (3,4). Changing k does not add rows, crop columns or wrap a one around an edge. The selected diagonal simply occupies the positions that fit within the requested rectangle.

Data type and memory order describe different choices

The examples request dtype=int so the printed entries are integers. Eye also accepts other data types; for example, dtype=bool produces true entries on the chosen diagonal and false entries elsewhere. The geometric pattern remains the same.

The order parameter chooses row-major or column-major storage in memory. It does not transpose the visible matrix or change which diagonal receives ones. Keep storage layout separate from the array's row and column interpretation.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the row count, column count, offset and data type beside each constructed diagonal pattern.

NumPy diagonal extracts diagonal entries and appends a diagonal axis

A diagonal can be useful as a sequence before any total is calculated. NumPy diagonal returns entries from a selected diagonal while keeping them available individually. Academia Master Trader presents this English lesson for readers in Madagascar, using constructed arrays to explain offsets, axis selection and the shape of the returned diagonal array.

A matrix diagonal becomes a one-dimensional sequence

After import numpy as np, define m = np.array([[5,7,9],[10,12,14],[15,17,19]]). The call np.diagonal(m) returns [5,12,19].

These are the entries at positions (0,0), (1,1) and (2,2). Their order follows the selected diagonal from its beginning towards increasing indices. The result has shape (3,), rather than the matrix shape (3,3).

Unlike trace, diagonal does not add the selected values. Unlike an upper triangular selection, it does not preserve the full matrix with excluded positions replaced by zero. Its output is the diagonal sequence itself.

NumPy diagonal extraction

An offset selects a parallel diagonal

The call np.diagonal(m,offset=1) returns [7,14]. A positive offset selects a diagonal above the main diagonal. The first selected position is row zero, column one.

The call np.diagonal(m,offset=-1) returns [10,17]. A negative offset selects a diagonal below the main diagonal, beginning at row one, column zero in this example.

Neither call moves entries within the matrix. Offset changes which coordinates are read. The two selected diagonals have length two, so both outputs have shape (2,).

Rectangular matrices also have diagonals. Their lengths depend on the matrix dimensions and the selected offset, rather than on an assumption that every diagonal has the same length.

The diagonal axis goes at the end

For arrays with more than two dimensions, axis1 and axis2 identify the matrix plane. Their defaults are zero and one. The remaining axes keep their relative order, and the diagonal axis is appended at the end.

Define layers = np.arange(8).reshape(2,2,2). The call np.diagonal(layers) returns [[0,6],[1,7]]. In contrast, np.diagonal(layers,axis1=1,axis2=2) returns [[0,3],[4,7]].

Both results have shape (2,2), yet their entries differ because the matrix planes differ. Shape alone cannot establish that the same diagonal selection was made. Record the meanings of both selected axes and the remaining axis.

Make an explicit copy before independent editing

The current NumPy documentation describes diagonal as returning a read-only view of the original array. It also describes historical and possible future changes to write behavior. Do not depend on editing that returned view to behave identically across versions.

Use d = np.diagonal(m).copy() when an independent, editable array is needed. For example, assigning d[0] = 99 then changes the copy without changing m. This separates diagonal extraction from a later decision to modify values.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the offset, selected axes, diagonal length and copying decision beside the extracted sequence.

NumPy trace adds diagonal entries and removes the two selected matrix axes

A diagonal total answers a different question from a row total or a complete matrix sum. NumPy trace adds entries along one diagonal within two selected axes. Academia Master Trader presents this English lesson for readers in Ethiopia, using constructed arrays to make diagonal offsets, axis defaults and output shape easier to follow.

Start with a diagonal rather than the entire matrix

After import numpy as np, define m = np.array([[4,6,8],[9,11,13],[14,16,18]]). The call np.trace(m) returns 33, because the main diagonal contains four, eleven and eighteen.

The result does not include every value in the matrix. It also does not produce three separate row totals. It reduces the selected diagonal to one sum. The original array remains available for another calculation.

The main diagonal joins positions whose row and column indices match. In this example, these positions are (0,0), (1,1) and (2,2). Thinking in coordinates helps separate the diagonal rule from the actual numbers stored there.

NumPy trace diagonal sum

Offset changes which diagonal contributes

The call np.trace(m,offset=1) returns 19, from six plus thirteen. A positive offset chooses a diagonal above the main diagonal, towards larger column indices.

The call np.trace(m,offset=-1) returns 25, from nine plus sixteen. A negative offset chooses a diagonal below the main diagonal, towards larger row indices.

Changing offset does not shift values inside the array. It changes the positions selected for addition. These shorter diagonals contain two entries, while the main diagonal in this square example contains three. Rectangular matrices can have diagonals of different lengths too.

Do not confuse this operation with returning the diagonal entries themselves. A diagonal extraction would preserve the contributing entries as a sequence; trace combines them into their total.

Higher-dimensional arrays need explicit axis attention

For trace, the default matrix axes are axis zero and axis one. They are not automatically the final two axes. This detail matters when an array stores several matrices in layers.

Define layers = np.arange(8).reshape(2,2,2). Then np.trace(layers) returns [6,8]. In contrast, np.trace(layers,axis1=1,axis2=2) returns [3,11].

Both outputs have shape (2,), but they describe different diagonal selections. A matching output shape therefore does not prove that two calculations selected the same entries.

The output shape removes axis1 and axis2 from the input shape. Write down the axes and their meaning before describing which remaining dimension labels the totals.

Choose an accumulator type deliberately when needed

Trace accepts dtype to choose the accumulator and returned data type. By default, an integer input narrower than the default integer precision is promoted for the sum; otherwise the input precision is used. An explicit dtype can make the intended accumulation type clear.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the diagonal offset, selected axes and expected output shape beside every trace calculation.