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

NumPy tile repeats an array as a block rather than repeating each element in place

Two outputs can contain the same values the same number of times and still arrange them differently. Academia Master Trader explains NumPy tile in English for readers in Iceland. We will repeat a small matrix across columns and down rows, then compare that block pattern with repeating individual elements. The aim is to read the repetition factors together with the original shape. A larger array in these examples is a constructed arrangement of existing data, not a record of additional observations or a financial outcome.

Define the block before repeating it

After import numpy as np, define a = np.array([[8,3],[2,9]]). Its shape is (2,2), which means two rows and two columns. Eight and three form the first row; two and nine form the second. This complete two by two arrangement is the block we will repeat. There are four elements in the input.

The function np.tile takes the input and a reps argument describing the number of repetitions along each axis. For our two dimensional input, a pair of factors can describe the row and column repetition separately. A factor of one keeps a single occurrence along that axis. It does not add an extra occurrence to the original.

Repeat the block across columns

The call np.tile(a,(1,2)) gives [[8,3,8,3],[2,9,2,9]] with shape (2,4). The row factor is one and the column factor is two. The original block appears twice across the column direction. The first output row is eight, three, eight and three. The second is two, nine, two and nine.

The order inside the repeated block is important. Eight is followed by three, not by another eight. The pattern is a copy of the whole two column width. Reading only the total number of eights would miss that structure. Follow the first input row as a sequence and you can see where one block ends and the next block begins.

Repeat the block down rows

The call np.tile(a,(2,1)) gives [[8,3],[2,9],[8,3],[2,9]] with shape (4,2). The row factor is now two and the column factor is one. The original two rows appear, followed by the same two rows again. The input's second row remains between the first and third output rows.

This differs from repeating each row twice in succession. That would place the first row immediately after itself, followed by two appearances of the second row. Tile instead repeats the complete row pattern of the block. The distinction can be seen without changing any numbers: compare the second output row, which is two and nine in our tiled result.

NumPy tile

Read the figure as separate calls

The figure shows the original block, the two explicit pairs of factors and the shorter call np.tile(a,2). Each output starts from the same input. The panels are not consecutive operations. With this two dimensional array, the single factor two is treated as repetition factors (1,2), so the shorter call also produces shape (2,4) and the same values as the column repetition panel.

The documentation explains this alignment rule more generally. When the input has more dimensions than the number of supplied factors, ones are placed before those factors. For a two dimensional input and one factor, that creates the pair one and two. Do not read the shorter call as a request to double every dimension. Here the number of rows remains two.

Compare block repetition with element repetition

For the same input, np.repeat(a,2,axis=1) gives [[8,8,3,3],[2,2,9,9]]. This has the same shape (2,4) as np.tile(a,(1,2)), but different positions. Repeat groups each element's appearances together; tile repeats the input block pattern. Matching shapes and matching element counts do not establish that two operations produced the same arrangement.

The NumPy documentation also advises using broadcasting operations and functions when the purpose is broadcasting, rather than using tile for that purpose. This lesson focuses on reading explicit tiled output. It does not claim that constructing repeated arrays is the best choice for every later calculation. Choose an operation from what the next step needs, not from the appearance of one small example alone.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the input block, match each factor to its axis and mark where the repeated block starts again. Then confirm the output shape. This keeps tile distinct from repeating individual elements and keeps constructed repetition separate from newly collected information.

NumPy repeat repeats elements along an axis rather than creating new observations

Seeing the same number twice in an output does not tell us why it appears twice. It may come from two measurements, or from a deliberate repetition of one stored value. Academia Master Trader explains NumPy repeat in English for readers in Denmark. A small matrix will show how the repetition count and the axis work together. We will compare a flat result, repeated values within rows and repeated complete rows. These examples describe array structure, not financial outcomes.

Establish the input and the repetition count

After import numpy as np, define a = np.array([[8,3],[2,9]]). The shape is (2,2), meaning two rows and two columns. The first row contains eight and three, and the second contains two and nine. There are four input elements. We will start with a repetition count of two and observe how the output changes when an axis is supplied.

In np.repeat(a,2), two is the total number of appearances requested for each input element in the result. It does not mean keeping the original and then adding two more appearances. Eight appears twice, not three times. Keeping that distinction clear makes the output size easier to understand before reading the printed values.

Read the flat default result

The call np.repeat(a,2) gives [8,8,3,3,2,2,9,9] with shape (8,). When axis is omitted, repeat uses the flattened input and returns a flat output. The input sequence is read as eight, three, two and nine. Each element is repeated immediately after itself before the operation moves to the next input element.

This is not the same arrangement as writing the whole sequence twice. Eight, three, two, nine, eight, three, two, nine would repeat the block. Our output instead groups each element's requested appearances together. Follow the first three output positions: eight, eight and three. That small check already distinguishes element repetition from repeating the complete input block.

Repeat along the column axis

The call np.repeat(a,2,axis=1) gives [[8,8,3,3],[2,2,9,9]] with shape (2,4). The two rows remain separate. Within each row, each column value appears twice in succession. The first row becomes eight, eight, three and three. The second becomes two, two, nine and nine. The output still has two rows but now has four columns.

Axis one identifies the dimension along which values are repeated. The repetition count controls how many appearances each element has there. The other dimension keeps its original length. In this example, four input elements produce eight output elements, but the two dimensional arrangement is retained because we explicitly selected the column axis rather than the flat default.

NumPy repeat

Repeat along the row axis

The call np.repeat(a,2,axis=0) gives [[8,3],[8,3],[2,9],[2,9]] with shape (4,2). The original first row appears twice before the original second row appears twice. The order inside each row remains unchanged. There are now four rows and two columns. This differs from placing a second complete copy of the matrix after the first.

The figure compares these two explicit axes with the flat default. Each result begins from the same input, not from the preceding result. Read its label and shape together. The column result has shape (2,4), the row result has (4,2) and the flat result has (8,). All contain eight elements, so the element count alone cannot identify the arrangement.

Different positions can have different counts

The documentation also allows an array of repetition counts. For np.repeat(a,[1,2],axis=0), the result is [[8,3],[2,9],[2,9]] with shape (3,2). The first row appears once and the second appears twice. Here the two counts correspond to the two positions along the selected row axis. They are not a request for a final shape of one by two.

Repetition changes the number of output elements, but it does not create independent measurements of the world. If a value represents one recorded observation, repeating it in an array is still a data operation on that recorded value. Explain repeated data as repeated data. A larger output array is not by itself evidence that more observations were collected.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the input shape, repetition count and selected axis before reading the result. Then count the appearances of one element and confirm the output shape. This keeps the meaning of repeat clear even when several output arrangements contain the same total number of elements.

NumPy roll moves values around an axis and brings the end back to the start

Moving values by one position sounds simple until a value reaches the edge of an array. Does it disappear, become a blank or return at the opposite end? Academia Master Trader explains NumPy roll in English for readers in Norway. A small matrix lets us distinguish a circular shift within each row from a shift across a flattened sequence. We will keep the input and each result separate so that the movement can be followed precisely. The examples describe data arrangement, not financial outcomes.

Record the input and the shift

After import numpy as np, define a = np.array([[8,3,6],[2,9,4]]). Its shape is (2,3), with two rows and three columns. The first row is eight, three and six. The second is two, nine and four. There are six elements. We will use a positive shift of one and compare calls that differ only in their axis argument.

The NumPy documentation states that elements moving beyond the last position return at the first position. Roll therefore does not fill the boundary with zeros or empty entries. The elements remain present, but their positions change. The output has the same shape as the input. In this lesson, every result still has two rows and three columns.

Shift the columns within each row

The call np.roll(a,1,axis=1) gives [[6,8,3],[4,2,9]]. Along axis one, each value moves one column position forward. Six leaves the last column of the first row and reappears in its first column. Eight moves to the middle and three moves to the last column. The second row follows the same rule independently.

Follow four as another example. It starts at position (1,2) and moves to (1,0). Its row coordinate stays one, because the shift is along the column axis. The wrapping happens within that row. Four does not move into the first row in this call. Naming the axis is what defines the boundary across which each value returns.

Shift the rows as complete units

The call np.roll(a,1,axis=0) gives [[2,9,4],[8,3,6]]. The second row moves past the final row position and returns as the first row. The original first row moves to the second position. Values keep their order within each row. Eight is still followed by three and six, while two is still followed by nine and four.

There are only two row positions in this input. Shifting by one along axis zero therefore exchanges the rows. This result happens to match reversing the row order for this particular two row matrix. That agreement does not make circular shifting and reversal the same operation in general. With more positions, their movement rules need not give the same arrangement.

NumPy roll

Understand the call without an axis

The call np.roll(a,1) gives [[4,8,3],[6,2,9]]. Without an axis argument, NumPy first flattens the input, shifts the resulting sequence and then restores the original shape. Here the flattened order starts as [8,3,6,2,9,4]. Shifting it by one produces [4,8,3,6,2,9], which is arranged back into two rows of three positions.

This explains why four reaches the first row in this result but stays in the second row for axis one. The two calls use different sequences for the circular movement. The figure shows both results alongside the axis zero result, all starting from the same input. Do not read the panels as successive steps. Each panel answers a separate question about the chosen axis.

Keep positions separate from new observations

Roll changes where existing values appear. It does not generate a new measured value for an empty boundary, and it does not represent a prediction of what comes next. In a time labelled dataset, the returning boundary value is an existing element from elsewhere in the sequence. A circular shift should therefore be described as circular, rather than silently presented as a newly observed period.

The shift amount and the axis are different parameters. The amount says how many positions to move; the axis says which ordered positions to follow. Leaving out the axis selects the flattened behaviour described above, not an automatic shift inside every row. Record both parameters when explaining an output so that another reader can reproduce the intended arrangement.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the input shape, choose the axis and follow the element at the boundary first. Then place the remaining values and confirm the restored shape. This makes circular movement visible and keeps it distinct from adding information or changing the values themselves.

NumPy flip reverses positions along selected axes while keeping the same shape

Reversing an array is a change of order, not a change of magnitude. A number can move to a different position without becoming larger or smaller. Academia Master Trader explains NumPy flip in English for readers in Sweden. Using a small matrix, we will compare reversing the row order, reversing the column order and reversing both. The aim is to connect each call with its axis and resulting positions. These are examples of data organisation, not financial outcomes.

Write down the input matrix

After import numpy as np, define a = np.array([[8,3,6],[2,9,4]]). The shape is (2,3): two rows and three columns. The first row contains eight, three and six. The second contains two, nine and four. There are six elements altogether. Before applying flip, identify these rows and columns so that the word reverse has a precise reference.

For this matrix, axis zero is the row axis and axis one is the column axis. Reversing an axis changes the order of positions on that axis. The NumPy documentation states that flip preserves the shape while reordering elements. We can therefore expect every result in this lesson to retain shape (2,3), even though the values appear in different places.

Reverse the row order

The call np.flip(a,axis=0) gives [[2,9,4],[8,3,6]]. The second row of the input comes first, followed by the original first row. The order inside each row stays the same. Two remains before nine and four, while eight remains before three and six. It is the order of rows that has been reversed.

Follow the value eight to make the movement concrete. It starts at position (0,0) and moves to (1,0). The row index changes, while the column index stays zero. The value four starts at (1,2) and moves to (0,2). Again, only the row coordinate changes. This is a position change along axis zero, not a swap between rows and columns.

Reverse the column order

The call np.flip(a,axis=1) gives [[6,3,8],[4,9,2]]. The rows remain in their original order, but the positions inside each row are reversed. Eight moves from (0,0) to (0,2), while six moves from (0,2) to (0,0). The middle value three stays in the middle of the first row.

Nine also stays in the middle of its row. An unchanged individual position does not mean that no reversal occurred. With three columns, the central column maps to itself when the column order is reversed. Read the whole arrangement and the selected axis, rather than using a single stationary element as evidence for what the operation did.

NumPy flip

Read the three separate results

The figure shows the input matrix and three results. Each result comes directly from the same input. They are not successive steps in one chain. The axis zero panel reverses rows. The axis one panel reverses columns. The panel without an axis argument reverses both axes, because the default applies flip along all input axes.

The call np.flip(a) gives [[4,9,2],[6,3,8]]. Eight moves from the first row and first column to the second row and last column. Both coordinates are reversed within their original axis lengths. The shape still has two rows and three columns. In this two dimensional example, np.flip(a,axis=(0,1)) expresses the same choice of axes explicitly.

Keep reversal distinct from other operations

Flip does not sort the values into increasing order. In the axis zero result, the first row is two, nine and four, which is not an increasing sequence. It also does not transpose the matrix. Transposing this input would exchange the row and column axes and produce shape (3,2). All flip results here retain (2,3). These operations answer different structural questions.

The documentation describes the result as a view of the input. Do not describe flip as a guarantee of an independent copy. A reordered view and separately stored data are different concepts. If another step will change elements, consider the relationship with the original array as well as the positions shown in the printed output.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Begin with the input shape, name the axis and follow a few values to their new coordinates. Finally, confirm that the shape is unchanged. This keeps reversal tied to a clear rule about positions instead of a vague impression that a matrix has been turned around.

NumPy expand dims adds a length one axis without adding new values

A list of three numbers can be stored in several array shapes. The numbers may stay the same while the structure around them changes. Academia Master Trader explains NumPy's expand dims operation in English for readers in Finland. We will start with a one dimensional array and follow three ways to insert new axes. The aim is to read the result from its shape, rather than assume that an extra dimension means extra observations. These examples describe data structure, not financial outcomes.

Record the starting array

After import numpy as np, define a = np.array([8,3,6]). Its shape is (3,). This means that the array has one axis with three positions. The comma is part of the tuple notation for a single entry. It does not indicate an empty second axis. Our input contains three elements, and its number of dimensions is one.

The function is written as np.expand_dims in code. It inserts an axis of length one at a chosen position in the expanded shape. That position is supplied through the axis argument. The operation does not invent a second observation for any of the numbers. It changes the way the same elements are arranged within axes. Keep the element count separate from the dimension count as you read each result.

Insert an axis before the existing axis

The call np.expand_dims(a,axis=0) produces [[8,3,6]] with shape (1,3). There are now two axes. The new first axis has length one, and the original three position axis comes after it. In an ordinary two dimensional table description, this is one row containing three values. The values remain eight, three and six in that order.

Notice that zero names a position in the result's axis order. It is not a request to create an axis of length zero. The inserted length is one. Reading axis as a length would lead to the wrong explanation of the array. Write the starting shape and the expanded shape beside the call so that the change can be checked directly.

Insert an axis after the existing axis

The call np.expand_dims(a,axis=1) produces [[8],[3],[6]] with shape (3,1). Here the original three position axis comes first and the inserted one position axis comes second. A table description is three rows with one value in each row. This result and the previous result contain the same number of elements, but they have different shapes.

Those shapes matter to later operations that match or combine arrays along axes. Do not treat (1,3) and (3,1) as interchangeable simply because their printed values look familiar. The position of the length one axis is the important difference. Expanding a shape is therefore a structural choice, not a calculation that makes the numbers larger.

NumPy expand dims

Read the figure through its shapes

The figure starts with shape (3,) and the values eight, three and six. Each row then pairs a function call with its resulting shape. The first row inserts an axis at position zero. The second inserts it at position one. The third inserts two axes in one call. Read each row independently from the same starting array, rather than treating the rows as consecutive changes.

For np.expand_dims(a,axis=(0,1)), the shape is (1,1,3). The new axes occupy positions zero and one in the expanded shape. The original axis of length three follows them. The array now has three dimensions and still contains three elements. The tuple identifies the positions of the inserted axes, not a pair of desired lengths for the whole result.

Separate a view from a new independent copy

The NumPy documentation describes the result as a view of the input with the number of dimensions increased. It should therefore not be presented as an independent copy of the values. A change of shape and a separate allocation of data are different ideas. If a later step will change elements, the relationship with the original data also needs attention.

This distinction is easy to miss when an array is displayed with extra brackets. Brackets show structure in the printed representation; they do not by themselves prove that new independent values were created. In our examples the element count stays three. The shape tells us where the added axes sit, while the documentation tells us how to describe the result's relationship to the input.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Start with the original shape, mark the inserted axis positions and write the final shape. Then read the values separately. This small habit keeps a new dimension from being confused with a new observation and makes the role of axis easier to explain.