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

NumPy squeeze tar bort axlar med längden ett utan att räkna om värdena

Ett flerdimensionellt fält kan innehålla axlar som bara har en position. Dessa axlar påverkar formen men ökar inte antalet värden. Academia Master Trader förklarar squeeze i NumPy på svenska för läsare i Finland. Med tre tal följer vi hur olika axlar kan tas bort och hur resultatets form förändras. Målet är att skilja mellan värden, antal element och antal dimensioner. Exemplen beskriver datastruktur och ska inte läsas som ekonomiska utfall.

Börja med formen

Efter import numpy as np skapar vi a = np.array([[[8],[3],[6]]]). Formen är (1,3,1). Den första axeln har längden ett, den andra längden tre och den sista längden ett. Fältet har tre dimensioner men bara tre element. De tre värdena är åtta, tre och sex. Hakparentesernas nivåer hör ihop med dimensionerna och betyder inte att fler tal har lagts till.

Anropet np.squeeze(a) ger [8,3,6] med formen (3,). När axis inte anges tar squeeze bort alla axlar vars längd är ett. I vårt fall försvinner både den första och den sista axeln. Axeln med längden tre finns kvar. Värdena summeras inte, sorteras inte och väljs inte ut efter storlek. Det är formen som förenklas, medan de tre elementen finns kvar.

Välj en bestämd axel

Med np.squeeze(a,axis=0) tar vi bara bort den första axeln. Resultatet blir [[8],[3],[6]] med formen (3,1). Den sista axeln har fortfarande längden ett, eftersom vi uttryckligen valde axel noll. Att en annan axel också skulle kunna tas bort betyder inte att den tas bort i samma anrop. Parametern axis avgränsar operationen.

Med np.squeeze(a,axis=2) blir resultatet i stället [[8,3,6]] med formen (1,3). Nu tas den sista axeln bort och den första finns kvar. Båda resultaten innehåller tre element, men deras former skiljer sig åt. Formen (3,1) beskriver tre rader med ett värde i varje, medan (1,3) beskriver en rad med tre värden. De är därför inte utbytbara bara för att talen är desamma.

NumPy squeeze

Läs figuren från anrop till form

Figuren visar utgångsformen och tre olika anrop, vart och ett med sin resultatform. För det första anropet försvinner båda ettorna i formen. För axis noll försvinner endast den första ettan. För axis två försvinner endast den sista. Läs axlarnas positioner från noll, i samma ordning som de står i formen. Då går det att se vilken dimension varje anrop påverkar.

De tre talen visas som en gemensam utgångspunkt eftersom inget av anropen ändrar vilka värden som finns. Skillnaden ligger i hur många axlar som omger dem och hur dessa axlar är ordnade. Skriv därför gärna upp både värden och form när du förklarar ett resultat. En utskriven följd av tal ger inte ensam hela bilden av fältets struktur.

Alla axlar kan inte tas bort

Anropet np.squeeze(a,axis=1) passar inte vårt exempel. Axel ett har längden tre, inte ett, och NumPy ger därför ValueError. Squeeze är ingen allmän funktion för att kasta bort en dimension med flera positioner. Den tar endast bort de valda axlar som har längden ett. Kontrollera formen innan du väljer axis, i stället för att tolka ett axelnummer som en önskad storlek.

Denna regel skiljer en axel från ett element. Att ta bort en axel med längden ett betyder inte att det enda värdet på den axeln raderas. Axeln tillför en nivå i strukturen, och det är den nivån som kan tas bort. Antalet lagrade element i vårt exempel förblir tre, oavsett vilken av de tillåtna varianterna vi använder.

Ett nolldimensionellt resultat är fortfarande ett fält

För b = np.array([[8]]) är formen (1,1). Anropet np.squeeze(b) tar bort båda axlarna och ger ett nolldimensionellt fält med formen (). Dokumentationen skiljer detta från en vanlig skalär. Ett resultat som skrivs ut som ett enda tal behöver alltså inte vara samma sorts objekt som ett fristående tal. Formen hjälper till att göra den skillnaden tydlig.

Dokumentationen anger också att resultatet är indatafältet självt eller en vy av det. Squeeze bör därför inte beskrivas som en garanti för en fristående kopia. Formändringen och frågan om gemensamt minne är olika saker. Om nästa steg ska ändra värden behöver även kopplingen till ursprungsfältet beaktas, inte bara hur resultatet ser ut på skärmen.

Lär dig vidare med Academia Master Trader på academiamastertrader.com.br och i Aprenda. Börja med formen, hitta axlarna med längden ett och välj vilka som ska tas bort. Anteckna sedan resultatets form. På så sätt blir squeeze en tydlig förändring av strukturen i stället för en oklar förändring av själva värdena.

NumPy transpose vertauscht Achsen und erhält die zugehörigen Werte

Zeilen und Spalten beschreiben die Anordnung einer Matrix. Werden ihre Rollen vertauscht, bleiben die Werte erhalten, aber ihre Positionen werden anders zugeordnet. Academia Master Trader erklärt transpose in NumPy auf Deutsch für Leserinnen und Leser in Belgien. Wir verfolgen eine Matrix mit zwei Zeilen und drei Spalten und lesen danach ihre transponierte Form. Das Beispiel zeigt eine strukturelle Veränderung von Daten, keine Berechnung eines finanziellen Ergebnisses. Wichtig sind die Ausgangsposition, die neue Position und die Form beider Arrays.

Die Ausgangsmatrix festhalten

Nach import numpy as np definieren wir a = np.array([[8,3,6],[2,9,4]]). Die Form ist (2,3). Die erste Zeile enthält acht, drei und sechs; die zweite enthält zwei, neun und vier. Die erste Spalte besteht aus acht und zwei, die zweite aus drei und neun, die dritte aus sechs und vier. Diese Zuordnungen sollten vor dem Aufruf klar sein, damit jede Veränderung nachvollziehbar bleibt.

Der Aufruf b = np.transpose(a) liefert [[8,2],[3,9],[6,4]]. Das Ergebnis besitzt die Form (3,2): drei Zeilen und zwei Spalten. Die erste Spalte der Eingabe wird zur ersten Zeile der Ausgabe. Entsprechend werden die zweite und dritte Spalte zu weiteren Zeilen. Kein Element wird addiert, entfernt oder anhand seiner Größe sortiert. Die sechs Werte werden über den Tausch der Achsen neu angeordnet.

Einzelne Positionen verfolgen

NumPy verwendet bei diesen Indizes die Zählung ab null. Der Wert drei steht in a an Position (0,1), also in der ersten Zeile und zweiten Spalte. Nach dem Transponieren steht er in b an Position (1,0), der zweiten Zeile und ersten Spalte. Für diese zweidimensionale Transposition werden Zeilenindex und Spaltenindex vertauscht. Der Wert selbst bleibt drei.

Auch der Wert vier lässt sich verfolgen: Aus Position (1,2) wird (2,1). Acht liegt zunächst an (0,0) und bleibt nach dem Tausch an (0,0). Eine Position mit gleichen Indizes kann also gleich aussehen, obwohl die Achsen insgesamt vertauscht wurden. Deshalb ist ein einzelnes unverändertes Element kein ausreichender Hinweis darauf, ob eine Matrix transponiert wurde. Lesen Sie mehrere Positionen und beide Formen zusammen.

NumPy transpose

Die Abbildung richtig lesen

Die Abbildung zeigt die Eingabe und das Ergebnis getrennt mit ihren Formen. Die Paare acht und zwei, drei und neun sowie sechs und vier stehen in der Ausgabe jeweils in einer Zeile. In der Eingabe bildeten sie die drei Spalten. An diesen Paaren lässt sich der Zusammenhang leichter erkennen als an einer bloßen Aufzählung der sechs Zahlen. Beide Tabellen enthalten dieselben Werte, aber mit vertauschten Rollen der Achsen.

Die Form ändert sich von (2,3) zu (3,2). Die Zahl der Elemente bleibt sechs. Daraus folgt nicht, dass jede Formänderung eine Transposition wäre. Auch andere Operationen können die Form eines Arrays verändern. Entscheidend ist hier die konkrete Zuordnung: Die neue erste Achse entspricht der früheren zweiten Achse, und die neue zweite Achse entspricht der früheren ersten Achse.

Ein eindimensionales Array bleibt eindimensional

Für v = np.array([8,3,6]) liefert np.transpose(v) weiterhin ein eindimensionales Array mit Form (3,). Es gibt nur eine Achse, deren Umkehrung keine zweite Achse erzeugt. Eine als Zeile gedruckte Folge wird durch transpose deshalb nicht automatisch zu einer zweidimensionalen Spalte. Die sichtbare Druckdarstellung und die tatsächliche Zahl der Achsen müssen getrennt betrachtet werden.

Für eine Spalte mit Form (3,1) ist eine zusätzliche Dimension nötig. Die Dokumentation nennt dafür unter anderem v[:,np.newaxis]. Diese Schreibweise ergänzt eine Achse, während transpose vorhandene Achsen umordnet. Das sind unterschiedliche Aufgaben. Prüfen Sie daher zuerst die Eingabeform, bevor Sie aus der gewünschten Darstellung ableiten, welche Operation passt. Drei Werte allein beschreiben noch nicht, ob eine oder zwei Dimensionen vorhanden sind.

Die allgemeine Achsenreihenfolge verstehen

Ohne den Parameter axes kehrt transpose die Reihenfolge der Achsen um. Für eine zweidimensionale Matrix ist das der bekannte Tausch von Zeilen und Spalten. Bei mehr Dimensionen betrifft die Umkehrung die gesamte Achsenreihenfolge. Mit axes lässt sich eine bestimmte Permutation angeben; jede ursprüngliche Achse muss darin genau einmal vorkommen. Diese Angabe ist eine Reihenfolge von Achsen, keine Liste der gewünschten Achsengrößen.

Die Dokumentation sagt außerdem, dass nach Möglichkeit eine Ansicht zurückgegeben wird. Eine Transposition sollte deshalb nicht allgemein als unabhängige Kopie beschrieben werden. Die neue Form und die sichtbare Anordnung beantworten nicht allein die Frage nach gemeinsamem Speicher. Für das Verständnis unseres Beispiels stehen die Positionen im Mittelpunkt; ein späterer Änderungsschritt muss den Speicherbezug zusätzlich berücksichtigen.

Lernen Sie mit Academia Master Trader auf academiamastertrader.com.br und im Bereich Aprenda weiter. Notieren Sie die Eingabeform, verfolgen Sie ausgewählte Positionen und prüfen Sie die Ergebnisform. So wird aus einem scheinbaren Drehen der Tabelle eine genaue Beschreibung der vertauschten Achsen.