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 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.

NumPy diagonal reads entries at linked row and column positions without adding them

A diagonal is a relationship between positions inside an array, not a judgement about which numbers matter most. Its entries can be read in order without sorting them or combining them into a total. Academia Master Trader explains NumPy diagonal in English for readers in Slovenia. A small square matrix lets us follow the main diagonal and compare positive and negative offsets. These examples describe data organisation. They do not describe financial outcomes or extra observations beyond the supplied integers. Each result will be checked against explicit coordinates.

Record the matrix before reading a diagonal

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 row and column indices run from zero through two. The value eight occupies (0,0), nine occupies (1,1) and one occupies (2,2). Those coordinates share the same row and column index within each pair.

The call np.diagonal(a) returns [8,9,1], with shape (3,). It follows the main diagonal from the upper left towards the lower right. The output is one dimensional because it records an ordered sequence of diagonal entries. It is not a smaller square matrix with the other entries filled with zeros. The original matrix is the source of the selected values.

Separate selection from addition

Reading [8,9,1] tells us which entries lie on the main diagonal and in which order they appear. It does not calculate their sum. Although those three integers could be added in a separate step, that would be a different operation. NumPy's documentation lists a separate function for summing diagonal entries. Keeping the operation names separate makes the intermediate structure easier to explain.

The numerical sizes of the entries do not determine whether they belong to the diagonal. Nine happens to be the largest supplied value, but eight and one are selected for the same positional reason. Six, at (0,2), is not on the main diagonal even though it is larger than one. The condition here concerns coordinates, not a numerical cutoff.

NumPy diagonal

Read the highlighted path in the figure

The figure highlights eight, nine and one inside the input matrix, then records the corresponding one dimensional output. Other input cells remain visible for context. Read the highlighted cells by increasing row index. This gives eight first, nine second and one third. The display does not show a time series or a price path; its positions refer only to this example matrix.

Follow nine in particular. Its input coordinate is (1,1), while its output index is one. A pair of coordinates in a matrix has become one position in the diagonal sequence. That change explains the output shape without requiring any change to the numerical value. The same reasoning applies to eight and one at the ends of the sequence.

Move above or below the main diagonal

The call np.diagonal(a,offset=1) returns [3,4], with shape (2,). It reads positions (0,1) and (1,2). The column index is one greater than the row index, placing these entries above the main diagonal. The output is shorter because only two such coordinate pairs fit within this matrix. The function does not invent a third entry to match the main diagonal length.

The call np.diagonal(a,offset=-1) returns [2,5], also with shape (2,). It reads positions (1,0) and (2,1), below the main diagonal. A negative offset does not mean taking negative numerical values or subtracting one from each entry. It selects a different diagonal according to the relationship between row and column positions. The entries themselves stay two and five.

Keep the scope of the example clear

A rectangular matrix can also have a diagonal. For b = np.array([[8,3,6],[2,9,4]]), whose shape is (2,3), np.diagonal(b) returns [8,9]. The main diagonal stops when no further matching row and column position is available. It does not require the input to be square, and it does not reuse the final row to reach the third column.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape and offset, list the selected coordinate pairs and only then write the output sequence. This keeps a diagonal selection distinct from a sum, a ranking or a rearrangement of every matrix entry.

NumPy compress selects slices using a one dimensional condition along an axis

A sequence of true and false entries can describe which positions to keep from an array. It is different from a sequence of integer indices because every condition entry corresponds to its own position along the selected axis. Academia Master Trader explains NumPy compress in English for readers in Slovakia. A small matrix lets us compare keeping columns, keeping rows and selecting from the flattened input. The examples describe data organisation, not financial outcomes or extra observations. Every output can be traced back to the supplied integers.

Start with the shape and condition

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. Define the condition as [True,False,True]. Its three entries refer to positions zero, one and two in that order. True keeps the corresponding position; false leaves it out. The condition itself does not contain the numerical values that will appear in the result.

The call np.compress([True,False,True],a,axis=1) gives [[8,6],[2,4]], with shape (2,2). Columns zero and two are kept, while column one is omitted. Both rows remain represented. The selected column order stays the same as in the source: the leftmost retained column comes before the rightmost retained column. The function does not sort the retained entries by value.

Match the condition to positions

The first true entry keeps eight and two together as one column. The false entry omits three and nine together. The last true entry keeps six and four together. This is a shared decision about columns across the matrix, not a separate numerical comparison for each individual cell. The selected axis tells us what a condition position addresses.

The output contains four entries because two retained columns each contain two rows. Counting true entries tells us the selected axis length in this example. It does not directly give the total element count of a multidimensional result. The unchanged dimensions still contribute to that total. Record the full output shape before describing the number of retained values.

NumPy compress

Read the figure as a position map

The figure places the condition beside the input matrix and shows the column result underneath. Follow four from input coordinate (1,2) to output coordinate (1,1). Its row position stays one, while its local column position becomes one because the original middle column was omitted. Nothing has been subtracted from the numerical value four. Selection changes the arrangement, not the retained values.

A false entry does not replace a column with zeros. The omitted column is absent from the output, so the shape changes from (2,3) to (2,2). This distinction matters when reading printed arrays: retaining a zero value and omitting a position are different operations. Our input contains no zero value, which keeps the contrast focused on the structure.

Select rows with the row axis

The call np.compress([False,True],a,axis=0) gives [[2,9,4]], with shape (1,3). The condition now addresses the two row positions. It omits the first row and keeps the second. All three columns remain in the output. The result is still two dimensional, even though it has only one row. The outer brackets record that retained row dimension.

The row condition has length two, matching the selected row axis. The earlier column condition had length three, matching the selected column axis. Naming the axis makes the meaning explicit rather than relying on the visual orientation of the printed matrix. A condition should be interpreted against the selected dimension, not against whichever dimension looks longest on screen.

Notice a shorter condition and an omitted axis

NumPy documents that a condition shorter than the selected axis limits consideration to that condition's length. Here np.compress([True,False],a,axis=1) gives [[8],[2]], with shape (2,1). The third input column is not considered. A short condition is therefore not automatically extended with true entries. Write the condition length beside the axis length to make that behaviour visible.

When axis is omitted, the function works on the flattened input. The call np.compress([True,False,True],a) gives [8,6], with shape (2,). It considers the first three flattened positions, not whole columns from both rows. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the selected axis, condition length and full output shape. Then trace a retained coordinate to explain exactly what was kept.

NumPy take selects positions in the requested order along a chosen axis

Selecting entries from an array requires a clear distinction between values and positions. Asking for index two does not mean asking for the numerical value two. Academia Master Trader explains NumPy take in English for readers in Czechia. We will use a small matrix to follow column selection, repeated indices and the default flattened interpretation. The supplied integers are enough to see each result directly. These examples describe data organisation rather than financial outcomes, rankings or additional observations beyond the original inputs.

Write the input with its coordinates

After import numpy as np, define a = np.array([[8,3,6],[2,9,4]]). Its shape is (2,3): two rows and three columns. Row indices are zero and one. Column indices are zero, one and two. The value six occupies (0,2), while four occupies (1,2). Both are in column two, even though neither has the numerical value two.

The call np.take(a,[2,0],axis=1) selects column two and then column zero. It gives [[6,8],[4,2]] with shape (2,2). The first output row comes from the first input row, and the second output row comes from the second input row. Within each row, the requested column order determines the result. Selecting columns does not reorder the rows.

Read the index sequence from left to right

The index list [2,0] is a sequence of instructions about positions. Its first entry chooses the third original column, and its second chooses the first original column. This is why six appears before eight in the first output row. The function does not sort the selected values and does not restore the columns to their original order after selecting them.

Changing the sequence to [0,2] changes the result to [[8,6],[2,4]]. The same two source columns are involved, but the output order is different. The shape remains (2,2). Shape alone therefore cannot describe which values were selected or how they are ordered. Keep the actual index sequence beside the resulting shape when recording a selection. A useful written record has a separate line for the source, the axis and the requested positions. This keeps the meaning visible even when the selected values happen to repeat or resemble their own index numbers.

NumPy take

Repeated indices repeat selected entries

The figure shows the input matrix and the output for columns two and zero. It labels the requested sequence separately from the input shape. Trace four from the second row's final column to the second output row's first column. The value remains four, while its local column coordinate changes from two to zero.

The call np.take(a,[1,1,0],axis=1) gives [[3,3,8],[9,9,2]], with shape (2,3). Index one appears twice in the sequence, so the corresponding column appears twice in the output. This is deliberate selection with repetition, not a newly measured entry. The selected axis length follows the length of this one dimensional index sequence, rather than the number of distinct indices.

Choose rows by naming the row axis

The call np.take(a,[1,0],axis=0) gives [[2,9,4],[8,3,6]], with shape (2,3). Now the sequence selects rows instead of columns. The second input row comes first, followed by the first input row. Each selected row keeps all three of its columns in their original order. The index list has the same numbers as a possible column list, but the axis changes what those numbers address.

For this matrix, row index two is outside the selected row axis, whose length is only two. Column index two is valid because the column axis has length three. Always check indices against the length of the named axis. A valid position on one axis is not automatically valid on another.

Distinguish an omitted axis from column selection

When axis is omitted, NumPy take uses the flattened input. Here np.take(a,[2,0]) gives [6,8], with shape (2,). It selects positions from the flattened sequence [8,3,6,2,9,4], rather than selecting whole columns from both rows. This differs from the explicit column result [[6,8],[4,2]]. The omitted argument changes the interpretation, not merely the printed layout.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, selected axis and ordered index sequence. Then trace one source coordinate into its output coordinate. Those checks separate a position request from a value request and make repeated selections easy to explain.

NumPy array split distributes an uneven axis across ordered sections

An array can be divided into a requested number of sections even when its selected length is not an exact multiple of that number. The important questions are how many entries each section receives and where the boundaries fall. Academia Master Trader explains NumPy's array split function in English for readers in Poland. We will work with eight supplied integers and then use a matrix to separate the meaning of axis from the meaning of section count. The examples describe data organisation, not financial outcomes or additional observations.

Record the input order

After import numpy as np, define a = np.array([8,3,6,2,9,4,7,5]). Its shape is (8,). The array has one axis with eight positions, numbered zero through seven. The printed values are not sorted. Their starting order is part of the example and will be preserved inside the returned sections. The function groups neighbouring positions; it does not group entries by their numerical size.

Call np.array_split(a,3). NumPy returns a list containing [8,3,6], [2,9,4] and [7,5]. Their shapes are (3,), (3,) and (2,). All eight entries appear once across these three sections. There is no padding value at the end and no extra observation. The final section is simply shorter than the first two.

Calculate section lengths before reading values

The documentation gives a quotient and remainder rule for an integer section count. With length eight and three sections, integer division gives two and the remainder is two. Two sections therefore receive one extra entry, giving lengths three, three and two. The longer sections appear first. This is a structural calculation about the axis length, not a calculation performed on the entries themselves.

The rule is not to give every leftover entry to the last section. That would produce lengths two, two and four, which is not this function's result. Nor does the function repeat the final value to make three equal sections. Writing the expected lengths before writing the actual entries makes both misunderstandings easier to spot. Their sum should match the selected input length.

Trace the boundaries

The first section takes original positions zero, one and two. The second takes positions three, four and five. The third takes positions six and seven. Nine begins at original index four and appears at local index one in the second section. Seven begins at original index six and appears at local index zero in the third section. Their values have not changed, but their local coordinates start again inside each output.

NumPy array split

The figure records the eight input entries and the three returned sections. Read its panels from left to right. The labels describe output lengths rather than ranking or numerical importance. The largest input value, nine, belongs in the middle section because of its original position. It is not moved into the first section because it is numerically larger than its neighbours.

Apply the same rule to a matrix

Define b = np.array([[8,3,6,2],[9,4,7,5]]), with shape (2,4). The call np.array_split(b,3,axis=1) divides four columns into widths two, one and one. Its outputs are [[8,3],[9,4]], [[6],[7]] and [[2],[5]], with shapes (2,2), (2,1) and (2,1). Both rows remain represented in every section. Only the selected column dimension is divided.

Changing the selected axis changes the length used in the rule. For np.array_split(b,2,axis=0), that length is two rows rather than four columns. The two outputs each have shape (1,4): [[8,3,6,2]] and [[9,4,7,5]]. Equal division works here too. Allowing uneven sections does not require every call to produce unequal shapes.

Distinguish a section count from an equal division requirement

NumPy split and array split have different behaviour when an integer section count does not divide the selected length evenly. For our one dimensional input, np.split(a,3) raises a ValueError, while np.array_split(a,3) gives the three sections shown above. Choose the rule that matches the structure you intend rather than treating the two function names as interchangeable.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape, selected axis and requested section count. Work out the output lengths, preserve entry order and trace one local coordinate in each section. Those checks explain an uneven division without confusing a shorter section with missing data.

NumPy split divides an array along an existing axis using equal sections or cut positions

Dividing an array is a question about positions before it is a question about numbers. A boundary separates neighbouring entries without sorting them or calculating a replacement value. Academia Master Trader explains NumPy split in English for readers in Lithuania. A small matrix lets us compare equal sections with explicit cut positions. We will record the input shape, name the selected axis and then read each output in order. These examples concern data organisation, not financial results or additional observations beyond the supplied values.

Begin with one matrix

After import numpy as np, define a = np.array([[8,3,6,2],[9,4,7,5]]). Its shape is (2,4): two rows and four columns. The first row is eight, three, six and two. The second row is nine, four, seven and five. Axis zero refers to the row dimension, while axis one refers to the column dimension. Each has its own length, so the same section count may have different meanings depending on the selected axis.

The NumPy documentation describes split as dividing an array into multiple subarrays that are views into the original. The result is a list of arrays, rather than one array with a new grouping axis. Keep the container and the individual output shapes separate when describing the operation. We will read the arrays in their returned order.

Divide the columns into equal sections

The call np.split(a,2,axis=1) returns two arrays. The first is [[8,3],[9,4]], and the second is [[6,2],[7,5]]. Each has shape (2,2). The selected axis has length four, and two equal sections each receive two columns. Both original rows remain represented in each output. The left section comes first, followed by the right section.

The integer two names the number of sections, not the number of columns to place in every section. Those descriptions happen to coincide here because four divided by two is two. With a different axis length, the same section count would produce a different section width. Read the argument's role rather than inferring it from this one numerical coincidence.

Divide the rows instead

The call np.split(a,2,axis=0) also returns two arrays, but each now has shape (1,4). They are [[8,3,6,2]] and [[9,4,7,5]]. The selected axis has length two, so each equal section receives one row. All four columns remain in each output. The extra brackets matter: these are two dimensional arrays with one row, not one dimensional arrays with four entries.

Follow seven across the examples. In the input it occupies (1,2). In the column division it belongs to the second output at (1,0). In the row division it belongs to the second output at (0,2). Its numerical value is unchanged. The boundary and the selected axis explain its new local coordinates.

NumPy split

Read explicit cut positions

The figure compares the input with the two equal column sections. Both outputs retain the original row order. The vertical boundary falls between column indices one and two. It does not represent a numerical threshold on the entries: three and four remain on the left because of their positions, not because of their sizes.

For a different arrangement, np.split(a,[1,3],axis=1) uses explicit cut positions. The returned arrays are [[8],[9]], [[3,6],[4,7]] and [[2],[5]], with shapes (2,1), (2,2) and (2,1). The first boundary is before column index one, and the second is before column index three. Two boundaries therefore create three sections. Equal widths are not required when explicit cut positions are supplied. The middle section contains the columns at original indices one and two. Its first local column is therefore not the first column of the input. Writing the original index range beside each section is a useful way to preserve that connection.

Check the selected length

An integer section count requires an equal division along the selected axis. For this input, np.split(a,3,axis=1) cannot divide four columns into three equal sections and raises a ValueError. The function does not silently distribute the remaining column. NumPy documents a separate function for near equal divisions; that is a different operation with its own rule.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, selected axis and whether the second argument means a section count or cut positions. Then write every output shape and trace one value through its local coordinates. This makes the division visible without mistaking boundaries for calculations.

NumPy stack joins equal shaped arrays along a new axis

Combining arrays can either extend an existing axis or add a new one. Those choices produce different structures even when the values come from the same inputs. Academia Master Trader explains NumPy stack in English for readers in Latvia. Two short one dimensional arrays let us see where the new axis appears and how that position changes the output. We will record shapes before following individual values. The examples describe data organisation, not financial outcomes or additional observations beyond the supplied inputs.

Start with two equal shapes

After import numpy as np, define a = np.array([8,3,6]) and b = np.array([2,9,4]). Each input has shape (3,): one axis with three positions. Array a contains eight, three and six; array b contains two, nine and four. We will supply them in the sequence (a,b), so a is the first input and b is the second.

The NumPy documentation requires every input to stack to have the same shape. This is more specific than having the same total number of elements. For our inputs, the full shape matches directly. Stack then joins them along a new axis, so the output has one more dimension than either input. Starting from one dimensional arrays, we will obtain a two dimensional result.

Put the new axis first

The call np.stack((a,b),axis=0) gives [[8,3,6],[2,9,4]] with shape (2,3). The new first axis has length two because we supplied two arrays. The original three position axis comes after it. In a table description, a becomes the first row and b becomes the second row. The values inside each input keep their original order.

Follow six to make the position clear. It starts at index two in a and appears at (0,2) in the output. Four starts at index two in b and appears at (1,2). The first coordinate identifies which input array supplied the value; the second identifies the original position within that input. This is the role of the new first axis.

Put the new axis last

The call np.stack((a,b),axis=1) gives [[8,2],[3,9],[6,4]] with shape (3,2). Now the original three position axis comes first and the new two position axis comes second. Each row pairs values that had the same index in the inputs. Eight is paired with two, three with nine and six with four.

Six now appears at (2,0) and four at (2,1). The first coordinate records their original position, while the second identifies their input array. Nothing has been sorted or averaged. The selected axis determines where the new input identifying dimension sits in the result. For these one dimensional inputs, axis minus one also selects the last position for the new axis.

NumPy stack

Read each panel from the same inputs

The figure shows both one dimensional inputs and the two output matrices. Each result comes directly from a and b. The panels are not a sequence in which the first output is transformed into the second. Read the call label together with the shape: axis zero gives (2,3), while axis one gives (3,2). Both outputs contain six elements from the supplied inputs.

The axis argument names the position of the new axis in the result. It is not an instruction to select an existing axis from a and change its length. This wording matters because each input has only one axis, yet the new axis may be placed before or after it. The result's axis order is the reference for interpreting the argument.

Compare a new axis with an existing axis

The call np.concatenate((a,b),axis=0) would give [8,3,6,2,9,4] with shape (6,). Concatenate extends the existing axis here. Stack instead introduces a new axis and gives a two dimensional arrangement. The six elements alone cannot tell us which operation was used. The shape and the grouping of values distinguish the results.

If c = np.array([7,5]), its shape (2,) does not match a's shape (3,). Stack does not fill a missing third position or repeat a value automatically. The equal shape requirement must be met before these arrays can be stacked. Check the complete input shapes rather than expecting a convenient printed layout to settle their compatibility.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the matching input shapes, count the input arrays and choose where their new axis will appear. Then trace two values with the same original index. This makes the extra dimension meaningful instead of treating stack as another name for any way of combining arrays.

NumPy concatenate joins arrays along an existing axis without inventing a new one

Combining two arrays requires more than placing their printed values next to each other. Their shapes must fit the axis along which they are joined. Academia Master Trader explains NumPy concatenate in English for readers in Estonia. We will use two small matrices to compare joining rows, joining columns and flattening before joining. The aim is to connect each output with a clear shape rule. These examples describe the organisation of numbers, not financial outcomes or additional observations beyond the supplied inputs.

Record both input shapes

After import numpy as np, define a = np.array([[8,3],[2,9]]) and b = np.array([[6,4],[7,5]]). Each array has shape (2,2), with two rows and two columns. Array a contains four elements and array b contains another four. We will pass them as a sequence using (a,b) inside the function call. The order of that sequence determines which input comes first.

The documentation states that concatenate joins arrays along an existing axis. Shapes must match except in the dimension selected by axis. For these two inputs, both dimensions match already, so either axis zero or axis one is available. We will keep the inputs unchanged and derive each result separately. One output is not the starting point for the next example.

Join along the row axis

The call np.concatenate((a,b),axis=0) gives [[8,3],[2,9],[6,4],[7,5]] with shape (4,2). The two rows from a come first, followed by the two rows from b. The number of rows becomes four, while the number of columns remains two. This is possible because both inputs have the same column length.

Follow the row six and four. In b it occupies the first row, at row index zero. In the result it appears after both rows of a, at row index two. Its two values remain together in their original order. Concatenate does not sort the rows by value. It joins the inputs according to the supplied sequence and selected axis.

Join along the column axis

The call np.concatenate((a,b),axis=1) gives [[8,3,6,4],[2,9,7,5]] with shape (2,4). The first row combines the first row of a with the first row of b. The second row combines their second rows. The number of rows remains two, while the number of columns becomes four. Both inputs must therefore agree in their row length.

The same eight input elements appear in both results, but their positions differ. Four appears at the end of the first output row when we join columns. When we join rows, it appears in the second column of the third output row. Reading only the total element count would not distinguish these arrangements. Shape and axis explain the difference.

NumPy concatenate

Read the figure and the flat alternative

The figure records the two input matrices and the two explicit axis results. It labels each result with its resulting shape. Read the row join as one matrix placed after the other along axis zero. Read the column join by matching corresponding rows along axis one. The new lengths belong to existing axes; the output is still two dimensional in both cases.

For np.concatenate((a,b),axis=None), the result is [8,3,2,9,6,4,7,5] with shape (8,). The arrays are flattened before joining. This is different from omitting the axis argument, whose default is zero. Writing None deliberately selects a flat result. Leaving the argument out in this example gives the row join, not the flat sequence.

Check the dimensions that must agree

Suppose c = np.array([[1,6]]), with shape (1,2). Joining a and c along axis zero works because their column lengths are both two. The result has shape (3,2). Their row lengths may differ because rows are the dimension being joined. The other dimension must match.

Joining a and c along axis one does not meet that rule: a has two rows and c has one. Concatenate does not automatically repeat c to fill the missing row. The shape requirement remains in force outside the selected axis. This is why checking each input shape before combining values is more useful than guessing from the appearance of a short printed array.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the input shapes, choose the existing axis and check every other dimension for agreement. Then write the output shape before tracing individual values. This makes joining arrays a precise structural operation rather than an ambiguous instruction to put numbers together.