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 flip reverses positions along an axis without changing the array shape

Reversing a sequence is not the same as sorting it. In NumPy, flip changes the order of elements along a chosen axis. The values occupy different positions, while the shape of the array stays the same. To understand the result, begin with the input order and the axis being reversed rather than with the numerical size of each value.

This distinction matters when a table represents an ordered collection. A reversed arrangement may be useful for reading or computation, but its meaning depends on how positions relate to the original data. The operation itself does not decide whether a row represents a date, a location or another category.

One sequence, read from the other end

Take the one-dimensional array 2,7,5. Applying flip produces 5,7,2. The final element moves to the first position, the first moves to the final position, and the middle element remains in the middle. The output still contains three elements and still has one dimension.

np.flip(a)

Notice that 5,7,2 is neither ascending nor descending numerical order. It is simply the original sequence read from the opposite end. If the input order changes, the reversed output changes with it. There is no comparison rule that places larger or smaller numbers first.

Original diagram showing input 2,7,5 reversed to output 5,7,2. Both arrays have shape (3,).

The diagram labels the input and output separately. It also states the shape so that the unchanged structure remains visible. A positional transformation can preserve the number of elements while changing how a reader interprets neighbours and endpoints.

Reversing rows in a matrix

Now consider a matrix with two rows. The first row is 2,7,5 and the second is 9,1,4. Its shape is (2,3): two rows and three columns. Flipping axis 0 reverses the order along the row dimension. The row 9,1,4 comes first, followed by 2,7,5.

np.flip(a, axis=0)

The order inside each row stays unchanged in this example. Only the order of the rows is reversed. A label such as reverse the table is therefore incomplete unless the intended axis is clear. Reversing rows and reversing the values within each row produce different layouts.

The output still has shape (2,3). Flip has not exchanged the roles of rows and columns. It is not a transpose, and it has not turned the matrix into a flat sequence. Inspecting the shape alongside the values makes these distinctions easier to keep separate.

Reversing columns instead

With axis 1, the operation reverses the order of columns. For our matrix, the first row becomes 5,7,2 and the second becomes 4,1,9. The two rows remain in their original order. Again, the shape is (2,3).

np.flip(a, axis=1)

This is the same matrix viewed with the position along each row reversed. It should not be described as changing the signs of its values. Positive values remain positive; negative values, if present, are not made positive merely by moving to another position.

NumPy also accepts negative axis numbers. They count from the last axis towards the first. For this two-dimensional matrix, axis -1 refers to its last axis, so it gives the same arrangement as axis 1. Naming the axis relative to the actual shape avoids treating -1 as a value to be reversed.

The default affects every axis

When the axis argument is omitted, its default is None. Flip then reverses all axes of the input. For our two-row matrix, the output rows are 4,1,9 followed by 5,7,2. Both the row order and the column order have been reversed.

np.flip(a)

This is different from reversing only axis 0 and different from reversing only axis 1. The one-dimensional example can hide this distinction because it has only one axis. Once the input has several dimensions, the default deserves an explicit explanation.

A tuple can name multiple axes to reverse. For a two-dimensional matrix, specifying (0,1) reverses both axes. In a higher-dimensional array, a tuple can select some axes while leaving the others in their existing order. The array shape remains unchanged in either case.

np.flip(a, axis=(0, 1))

A view is not an independent copy

The NumPy documentation states that flip returns a view of the input with the selected entries reversed. A view is not an independent copy of the numerical data. Treating the result as a separate workspace for edits can therefore have consequences for the source array.

For a writable NumPy array, changing an element through the reversed view can change the corresponding element in the original array. If an independent result is required for later changes, make that requirement explicit and create a copy rather than assuming the positional reversal has already done so.

This is a different question from whether the original array has been reordered in place. Merely obtaining the flipped view does not rewrite the input into the displayed reversed order. Shared data and in-place reordering should not be confused: the view presents an alternative order over the same underlying values.

Describe the transformation precisely

A clear explanation of flip includes the input shape, the selected axes and a small example of the resulting order. For a matrix, show at least enough values to distinguish row reversal from column reversal. State whether later work will use the view directly or needs independent data.

Academia Master Trader publishes educational material about data organisation and numerical methods. Visit academiamastertrader.com.br to explore further topics and continue learning. Read a reversed array by tracing its positions, not by assuming that reversal means sorting, transposition or a change in numerical signs.

Aprenda

NumPy tile repeats a whole pattern, not each value in a group

A repeated pattern and a repeated element are different structures. In NumPy, tile constructs an array by repeating the input array. This makes it useful to read the input as a block: the order inside that block carries through to each repetition. The result can be longer or have more dimensions, depending on the repetition argument and the shape of the input.

Understanding the block is more useful than simply counting how many times a number appears. Two operations may produce outputs with the same number of elements while arranging those elements differently. A clear explanation therefore needs the input, the repetition argument, the resulting order and the resulting shape.

Start with a two-value pattern

Suppose a one-dimensional array contains 2 followed by 5. Asking tile for three repetitions produces 2, 5, 2, 5, 2, 5. Each copy preserves the two-value pattern. The first copy occupies the first two positions, the second occupies the next two, and the third occupies the final two.

np.tile(a, 3)

The repetition argument counts copies of the input pattern in this example. It does not mean three extra copies in addition to the original. Two values repeated as a block three times give six output elements. Keeping the copy count explicit helps explain both the length and the arrangement of the output.

Original diagram showing the input pattern 2,5 repeated as three blocks. The output order is 2,5,2,5,2,5.

The diagram places a border around each copy. Those borders are explanatory labels, not additional data stored by tile. The actual output is one array. A reader should be able to recover its full sequence without relying only on the number of boxes or on colour.

Contrast blocks with individual elements

For the same input 2,5, repeating each element three times gives 2,2,2,5,5,5. That is the behaviour of repeat with a scalar repetition count. Tile instead gives 2,5,2,5,2,5. Both outputs contain six values, including three occurrences of 2 and three occurrences of 5, but their positions differ.

np.repeat(a, 3)

This comparison shows why a frequency count alone cannot describe an array transformation. If later calculations depend on neighbours or position, the arrangement matters. State whether the intended operation repeats the whole pattern or repeats the individual elements before choosing the function.

Neither operation creates a new observation from the outside world. A longer output is a constructed arrangement of the input. If the source contains two recorded values, the six output positions should not be described as six independently recorded values merely because the array is longer.

Read a repetition tuple by dimension

A tuple can describe repetitions along multiple dimensions. With our one-dimensional input 2,5, the argument (2,3) produces two rows. Each row contains the input pattern three times, so each row is 2,5,2,5,2,5. The complete result has shape (2,6).

np.tile(a, (2, 3))

NumPy treats the one-dimensional input as having an added leading dimension for this operation. Its shape is considered as (1,2) before the repetition factors are applied. Repeating that structure twice along the first dimension and three times along the second gives two rows and six columns.

The tuple does not request two occurrences of the value 2 and three occurrences of the value 5. Its entries describe repetitions along dimensions. That interpretation is different from passing per-element repetition counts to repeat, even if the written numbers look similar.

A matrix keeps its internal arrangement

Now take a two-by-two input. Its first row is 2,5 and its second row is 7,9. Using the repetition tuple (2,1) stacks two copies of the entire matrix vertically. The rows are 2,5 ; 7,9 ; 2,5 ; 7,9. The output has four rows and two columns.

np.tile(a, (2, 1))

This does not duplicate the first row beside itself before moving to the second row. The original two-row block stays intact. Describing the block first makes the result easier to read than a vague instruction to double the rows.

For the same matrix, a scalar repetition argument of 2 repeats along the last dimension. The first row becomes 2,5,2,5 and the second becomes 7,9,7,9. The result has two rows and four columns. In this case, NumPy extends the repetition specification with a leading factor of one.

np.tile(a, 2)

Check shape as well as length

The documentation describes dimension promotion explicitly. If the repetition specification has more dimensions than the input, leading dimensions are added to the input. If the input has more dimensions than the repetition specification, leading ones are added to that specification. These rules matter when the expected layout has several dimensions.

A useful reading routine is to write down the input shape, align the repetition factors with its dimensions, and then inspect the output shape and values. Avoid inferring the intended dimensions from the total number of elements alone. Different shapes can hold the same element count while expressing different arrangements.

The documentation also recommends NumPy broadcasting operations and functions when the aim is broadcasting, rather than using tile for that purpose. Learning to recognise a repeated block does not mean that making an explicitly tiled array is the appropriate choice for every numerical calculation.

Academia Master Trader publishes educational material about data organisation and numerical methods. Visit academiamastertrader.com.br to explore further topics and continue learning. When reading tile, identify the whole input pattern first, then explain the repetition factors and the output shape without confusing copied positions with new observations.

Aprenda

NumPy repeat répète les éléments à leur place, sans inventer de nouvelles observations

Allonger un tableau ne signifie pas toujours recueillir de nouvelles données. Une opération peut simplement répéter les éléments qui existent déjà. C'est le rôle de repeat dans NumPy : chaque élément est répété à la suite de lui-même, selon le nombre demandé. Le résultat contient davantage de positions, mais ces positions proviennent des données d'entrée.

Cette distinction aide à présenter correctement un tableau transformé. Si une valeur apparaît plusieurs fois après l'opération, cela ne prouve pas qu'elle a été observée plusieurs fois dans la source. Il faut distinguer les observations originales des répétitions produites par le calcul.

Deux valeurs répétées trois fois

Prenons un tableau à une dimension contenant 2 et 5. En demandant trois répétitions pour chaque élément, nous obtenons 2, 2, 2, 5, 5, 5. Les trois occurrences de 2 sont regroupées, puis viennent les trois occurrences de 5. Le résultat n'alterne pas entre les deux valeurs.

np.repeat(a, 3)

Le paramètre 3 représente ici le nombre total d'occurrences de chaque élément dans la sortie. Il ne demande pas de conserver l'élément original puis d'ajouter trois copies supplémentaires. Avec deux éléments répétés trois fois, la sortie contient six éléments, et non huit.

Schéma original : les valeurs d'entrée 2 et 5 sont chacune répétées trois fois. La sortie contient 2, 2, 2, 5, 5, 5, dans cet ordre.

Le schéma sépare les deux valeurs de départ des six positions obtenues. Les groupes rendent visible la règle de répétition. Cette règle décrit la construction de la sortie ; elle ne décrit pas une nouvelle collecte de mesures et n'ajoute aucune information sur la fréquence réelle des valeurs dans une population.

Conserver le sens des données transformées

Un tableau répété peut être utile pour préparer une structure de calcul. Toutefois, sa longueur ne doit pas être présentée comme le nombre d'observations indépendantes de la source. Dans notre exemple, les données de départ comportent deux éléments. Les six éléments de sortie résultent d'une transformation explicite.

Il est donc utile de nommer séparément le tableau source et le tableau répété. Une légende peut préciser le nombre de répétitions utilisé. Cela permet à une autre personne de comprendre pourquoi certaines valeurs se suivent plusieurs fois, sans supposer qu'il s'agit d'une série enregistrée telle quelle.

La répétition ne trie pas non plus les valeurs. Dans l'exemple, 2 précède 5 parce que cet ordre existe dans l'entrée. Si les valeurs de départ étaient 5 puis 2, les groupes suivraient cet autre ordre. Le regroupement provient de la répétition de chaque élément, pas d'un classement numérique.

Un nombre différent pour chaque élément

Le paramètre repeats peut aussi recevoir un tableau de nombres entiers. Pour les valeurs 2 et 5, choisir respectivement une et trois occurrences donne 2, 5, 5, 5. Les deux éléments ne contribuent alors pas au même nombre de positions dans la sortie.

np.repeat(a, [1, 3])

Cette écriture associe chaque nombre de répétitions à l'élément correspondant. Le premier nombre concerne la première valeur, et le second concerne la seconde. Avant de lire le résultat, il faut donc vérifier à la fois le contenu du tableau et l'association entre positions et répétitions.

La documentation précise que repeats est diffusé pour correspondre à la forme de l'axe concerné. Dans un exemple simple à deux éléments, cette association reste facile à lire. Dans un tableau plus grand, la forme des paramètres fait partie du sens de l'opération et doit être examinée avec le résultat.

L'axe décide de ce qui est répété

Considérons maintenant un tableau de deux lignes et deux colonnes. La première ligne contient 2 et 5, la seconde contient 7 et 9. Avec axis=0 et deux répétitions, chaque ligne est répétée. La sortie contient successivement les lignes 2,5 ; 2,5 ; 7,9 ; 7,9.

np.repeat(a, 2, axis=0)

Le tableau de sortie possède alors quatre lignes et deux colonnes. L'opération n'a pas ajouté de nouvelles valeurs à l'intérieur de chaque ligne. Elle a répété les éléments le long de l'axe des lignes, en conservant la structure des autres dimensions.

Avec axis=1, chaque valeur est répétée dans sa ligne. La première ligne devient 2,2,5,5 et la seconde devient 7,7,9,9. Le résultat possède deux lignes et quatre colonnes. Les mêmes données d'entrée conduisent donc à des formes différentes selon l'axe choisi.

np.repeat(a, 2, axis=1)

Dire seulement que le tableau a été doublé ne suffit pas pour décrire ces résultats. Il faut préciser l'axe et la forme obtenue. Quatre lignes de deux colonnes et deux lignes de quatre colonnes ont le même nombre d'éléments, mais ne représentent pas la même organisation.

Sans axe, la sortie est à une dimension

Par défaut, repeat utilise l'entrée aplatie et renvoie un tableau à une dimension. Pour notre tableau à deux lignes, la séquence aplatie est 2,5,7,9. Avec deux répétitions, la sortie est 2,2,5,5,7,7,9,9. La structure en deux lignes n'est pas conservée dans cette sortie par défaut.

np.repeat(a, 2)

Ce comportement explique pourquoi le nombre d'éléments ne suffit pas à vérifier une transformation. La sortie contient bien huit éléments, comme les versions avec un axe explicite, mais sa forme est différente. Une lecture correcte associe toujours les valeurs, l'axe et la forme du tableau.

Academia Master Trader propose des contenus pédagogiques sur l'organisation des données et les méthodes numériques. Consultez academiamastertrader.com.br pour découvrir d'autres sujets et poursuivre votre apprentissage. Pour lire une répétition, identifiez les éléments sources, le nombre d'occurrences demandé et l'axe utilisé, sans confondre positions créées et nouvelles observations.

Aprenda

NumPy clip limits values to boundaries without removing their positions

Some array operations select observations. Others change the values stored at the existing positions. NumPy's clip belongs to the second group: it limits values to the edges of a specified interval. Values below the lower boundary become that boundary, and values above the upper boundary become the upper boundary.

This is a numerical transformation, not a deletion rule. It does not mean that observations outside an interval disappear from the result. Understanding that distinction is useful when comparing an original array with a processed array, because the same positions can now contain different numbers.

Follow each input to its output

Suppose a one-dimensional array a contains -2, 3, 8, and 12. We choose a lower boundary of 0 and an upper boundary of 10. The first value, -2, becomes 0. The middle values 3 and 8 stay as they are. The final value, 12, becomes 10. The output is 0, 3, 8, 10.

np.clip(a, 0, 10)

The output has four elements, just like the input. Nothing has been removed from this example. Two values have changed and two have stayed the same. The result should therefore be described as a bounded version of the input, not as a smaller selection of the original observations.

Original diagram showing inputs -2, 3, 8, 12 and clipped values 0, 3, 8, 10 for lower boundary 0 and upper boundary 10. Corresponding positions are aligned.

The figure aligns the original and transformed values by position. It shows why clipping is different from filtering: the first and last positions remain present. They now hold boundary values. A reader looking only at the output would not know how far the original values were outside the interval.

A boundary is a rule, not a recovered observation

The new zero in the first position was chosen by the transformation rule. It does not mean that the original observation was zero. Likewise, the final 10 does not show that the last input was exactly 10. The original values were -2 and 12, and the clipping rule replaced them.

This matters when naming an array or writing a caption. Original observations and clipped values are different data products. Keep that difference visible rather than presenting the transformed array as though nothing has changed. A short statement of the lower and upper boundaries helps the reader understand the result.

Clipping also does not rescale the whole array to fill the interval. In the example, 3 stays 3 and 8 stays 8. The function has not stretched the spacing between the interior values or converted their units. It has applied the specified lower and upper limits.

Values at the edges stay at the edges

NumPy describes replacements for values smaller than the lower boundary and larger than the upper boundary. A value already equal to a boundary is already within the requested limits. For an input of 0, 4, 10 with boundaries 0 and 10, the returned values remain 0, 4, 10.

Several different inputs can produce the same clipped output. For instance, both -2 and -5 would become 0 under this rule. The output alone therefore cannot reconstruct those original inputs. Preserve the original array separately when the later explanation needs the original measurements.

Choosing boundaries is a separate decision from calling the function. The software can apply the numbers it receives, but those numbers still need a meaning in the workflow. This example uses small integers to explain array behaviour. It does not establish suitable limits for an unrelated dataset.

One-sided clipping uses None

The documentation allows None for either boundary. Using None for the lower edge leaves that side unclipped. Using None for the upper edge leaves the upper side unclipped. This makes it possible to state a one-sided rule rather than supplying an artificial second boundary.

For our original input, clipping only above 10 gives -2, 3, 8, 10. The value -2 remains unchanged because there is no lower limit in that call. Clipping only below 0 gives 0, 3, 8, 12 instead. The value 12 stays unchanged because that call supplies no upper limit.

np.clip(a, None, 10)

np.clip(a, 0, None)

Read both arguments when explaining the result. A single boundary does not imply that the opposite side has been set to zero or to another default number. It means that clipping is not performed on that edge.

Output placement and boundary order

The out argument can place the result into a supplied array, including the input array for an in-place operation. NumPy's documentation includes that use. It changes where the result is written, so an explanation should not promise that the original array remains available after an in-place call.

np.clip(a, 0, 10, out=a)

That form should be used deliberately. A separate result array and an in-place transformation may produce the same displayed numbers while leaving different data available for later steps. Check which object is being read when comparing before and after values.

The order of the boundaries also needs attention. NumPy states that clip does not check whether the lower boundary is smaller than the upper boundary. Its documented behaviour when the lower argument exceeds the upper argument is to return values equal to the upper argument. Do not interpret reversed arguments as an instruction to swap the limits automatically.

Academia Master Trader publishes educational material about data organisation and numerical methods. Visit academiamastertrader.com.br to explore more topics and continue learning. When reading a clipped array, state the boundaries, identify which values changed, and keep the transformed result distinct from the original observations.

Aprenda

NumPy diff describes changes between neighbours, not the original values

A sequence of measurements and a sequence of changes answer different questions. The original values tell us what was recorded at each position. First differences tell us how one recorded value compares with its neighbour. NumPy's diff calculates discrete differences along an axis, using the next element minus the current element for a first difference.

Keeping those roles separate makes a numerical explanation easier to follow. A difference is not a replacement label for the original observation. It comes from a pair of observations. Before interpreting the result, identify the order of the input and the axis along which the pairs are formed.

Four observations produce three first differences

Suppose a one-dimensional array a contains 4, 7, 6, and 10. The difference from 4 to 7 is 3. The difference from 7 to 6 is minus 1. The difference from 6 to 10 is 4. The first-difference output is therefore 3, -1, 4.

np.diff(a)

There are three results because four neighbouring values form three adjacent pairs. Without adding boundary values, there is no earlier input to pair with the first observation. The function does not invent that missing value simply to make the output as long as the input.

Original diagram showing inputs 4, 7, 6, 10 and first differences 3, -1, 4. Each difference sits between the neighbouring inputs used to calculate it.

The figure places each result between the two inputs that produce it. This layout makes the pairing explicit. The result -1 describes the move from 7 to 6. It does not say that either original observation was negative, and it does not describe the distance from the first input to the last.

Read the subtraction in the right order

The order of subtraction matters. NumPy documents the first difference as the next element minus the current element. Reversing those terms reverses the sign for ordinary signed-number examples. A positive result in this example indicates that the next value is greater; a negative result indicates that it is smaller.

The number 3 is an absolute difference in the units of these inputs. It is not automatically a percentage change or a rate per unit of time. Those interpretations require their own definitions and, where relevant, the spacing between observations. Calling diff alone does not supply that extra information.

For clarity, label a column of output as adjacent differences rather than simply values. A reader should not need to infer whether a number is an observation, a change, an index, or a total. A short label can preserve the meaning of a calculation when the result is moved into a table or report.

Second differences compare the first differences

The n argument controls how many times the differencing operation is applied. For the example, the first differences are 3, -1, 4. Applying the same rule again gives -4 and 5: minus 1 minus 3 is minus 4, and 4 minus minus 1 is 5.

np.diff(a, n=2)

A second difference is therefore not found by subtracting two from each input. Nor does it simply mean comparing an input with the observation two positions ahead. NumPy describes higher differences as repeated applications of diff. The output of one stage becomes the input to the next stage.

With these four inputs, first differencing produces three elements and second differencing produces two. This shrinking dimension belongs to the calculation. Preserve it in an explanation instead of silently attaching the results to every original position as if no pairing had taken place.

The default axis is the last axis

Consider a two-row, three-column array. The first row contains 4, 7, 6. The second row contains 2, 5, 9. By default, diff operates along the last axis. For this two-dimensional array, that forms adjacent pairs within each row. The first output row is 3, -1; the second is 3, 4.

np.diff(a)

Each row is handled separately. The function does not continue from the last input in the first row to the first input in the second row. This differs from a function that flattens the entire input by default. Read the documented axis rule for the specific operation rather than carrying a default over from another function.

With axis=0, the pairs are formed down the rows within each column. Subtracting the first row from the second gives one output row containing -2, -2, 3. The input still has the same values, but the neighbouring positions used in the calculation have changed.

np.diff(a, axis=0)

Boundary values and data types need explicit choices

The prepend and append arguments can supply values before or after the input along the selected axis, before differencing takes place. These are additional calculation inputs. They should have a stated meaning. Adding a zero just to preserve a length changes the first comparison, rather than recovering an observation that was present all along.

The data type also affects how the output should be read. NumPy notes that unsigned integer arrays retain unsigned results. Its documented example of subtracting zero minus one in an unsigned eight-bit array gives 255. To obtain a signed difference for that example, the input is converted to a suitable signed integer type first.

The examples here use ordinary signed integers to explain the pairing and the signs. Other types have their own behaviour. NumPy documents that differences between datetime values can produce timedelta values, for instance. Check the input type alongside the axis and the number of differencing steps.

Academia Master Trader publishes educational material about data organisation and numerical methods. Visit academiamastertrader.com.br to explore more topics and continue learning. When reading a difference, identify the pair of inputs, the subtraction order, and the units before assigning a meaning to the result.

Aprenda

NumPy cumprod keeps a running product, not a running sum

A sequence can describe individual values, a total, or a calculation that develops one position at a time. These are different views of the same data. NumPy's cumprod returns cumulative products along an axis. Each output records the product reached at that position, including the current input. It does not add the values together.

This distinction is useful before writing code. A running sum answers how much has been added so far. A running product answers what the values have multiplied to so far. The function name does not decide which question your data requires. That choice comes from the meaning of the inputs and the question you want to answer.

Four inputs, four intermediate products

Suppose a one-dimensional array a contains 2, 3, 2, and 4 in that order. The first cumulative product is 2. Multiplying by the next input gives 6. Multiplying that result by 2 gives 12. The final multiplication by 4 gives 48. The output is therefore 2, 6, 12, 48.

np.cumprod(a)

There are four output elements, not just one final total. The last element describes the product of all four inputs. Earlier elements describe shorter prefixes of the same sequence. The second output, for example, is the product of the first two inputs, not a replacement measurement for the second input.

Original diagram showing inputs 2, 3, 2, 4 and cumulative products 2, 6, 12, 48, with corresponding positions aligned.

The figure separates inputs from accumulated results. Matching positions are aligned so that the reader can see what each output includes. The number 12 belongs to the third output because it combines the first three inputs. It is not the sum of those inputs, and it does not describe the third input alone.

Multiplication is not addition

For the same inputs, a cumulative sum would be 2, 5, 7, 11. A cumulative product is 2, 6, 12, 48. Both outputs retain information at each position, but the operation connecting those positions is different. Similar output shapes do not make the results interchangeable.

Labels should name the operation rather than simply say accumulated values. A reader who sees a rising sequence cannot infer whether it came from addition, multiplication, or another rule. Writing cumulative product beside the result gives the sequence an explicit meaning without requiring someone to reconstruct the calculation.

Nor should a numeric example be treated as a claim about a real-world outcome. Here the inputs are small integers chosen to explain array behavior. Their multiplication illustrates a computation. It does not establish what operation is suitable for an unrelated dataset or what any measured process will do.

The axis defines where each sequence starts

Now consider a two-row, three-column array. The first row contains 2, 3, 2. The second row contains 4, 2, 5. With axis=1, cumprod works across the columns within each row. The first output row is 2, 6, 12. The second output row is 4, 8, 40.

np.cumprod(a, axis=1)

Each row starts its own cumulative calculation. The first output in the second row is 4. It does not continue multiplying from the last result in the first row. This is why the axis is part of the explanation, not a minor display choice added after the numbers have been calculated.

With axis=0, the cumulative calculation moves down the rows within each column. The first output row is 2, 3, 2. The second output row is 8, 6, 10. Each second-row value combines the two inputs from its own column.

np.cumprod(a, axis=0)

The input has not changed between these calls. What changes is the set of sequences used for accumulation. Report the axis together with the result so that a reader knows whether each output belongs to a row sequence or a column sequence.

Omitting the axis changes the structure

The NumPy documentation says that cumprod flattens its input by default. For the two-row example, the flattened sequence is 2, 3, 2, 4, 2, 5. Its cumulative products are 2, 6, 12, 48, 96, 480. This is one sequence rather than two independent row sequences.

The output still has six elements, but it is not the same result as the two-dimensional row calculation. Equal element counts do not imply equal meaning. Before placing a result beside another array, check which input positions contributed to each accumulated value.

Data type belongs in the explanation

The dtype argument controls the type used for the returned array and for the accumulator that performs the multiplications. NumPy documents a default rule based on the input type, including promotion of lower-precision integer inputs to the platform's default integer type. Do not assume that every input type follows an identical path.

The documentation also notes that integer arithmetic is modular and does not raise an error on overflow. That is a property to account for when choosing a type. The small examples here explain the order of multiplication; they do not remove the need to consider the numeric range of another calculation.

Academia Master Trader publishes educational material about data organization and numerical methods. Visit academiamastertrader.com.br to explore more topics and continue learning. When reading a cumulative product, identify the input order, the axis, and the data type before explaining what each output position represents.

Aprenda

NumPy cumsum:累積總和保留每一步,不只是最後的合計

閱讀一串數據時,我們有時需要知道全部數值的合計,有時則想知道每走到一個位置,之前的數值已經累積了多少。這兩個問題並不相同。NumPy 的 cumsum 用來計算累積總和,結果記錄沿指定軸逐步相加的數值,而不是只交出一個最後答案。

理解這個分別,可以先把注意力放在資料的順序。累積總和會依照輸入中的位置前進。它不會先把數值由小至大排列,也不是尋找最高值或最低值。每個輸出位置都有自己的意思:從該段序列起點,到目前位置為止的合計。

四個數值,四個累積結果

假設一維陣列 a 的數值依次是 2、3、1、4。第一個累積結果是 2。加入第二個數值 3 後,累積結果是 5。再加入 1,得到 6。最後加入 4,得到 10。因此輸出依次是 2、5、6、10。

np.cumsum(a)

這個結果仍有四個元素,與輸入的元素數目相同。數值 10 是最後一個累積結果,但前面的 2、5、6 並非多餘資訊。它們分別描述計算走到不同位置時的合計。只保留最後一個數值,就無法從輸出直接看到這段累積過程。

原創示意圖:輸入數值依次為 2、3、1、4;累積總和依次為 2、5、6、10。每個位置保留當時的合計。

圖中把輸入與輸出分成兩行,並讓相同位置對齊。第一個輸出對應第一個輸入,第二個輸出包含前兩個輸入,如此類推。閱讀時應把每個位置連同其之前的資料一起理解,而不是把輸出當作一組與順序無關的數字。

累積總和與單一合計

sum 與 cumsum 的用途有別。前者計算合計;後者保留沿序列前進時的各個累積結果。在這個整數例子中,所有輸入的合計是 10,而累積總和的最後一項也是 10。不過,兩種輸出的結構與可回答的問題不同。

如果報表只需要一個合計,顯示整串累積結果可能不是所需的表達方式。如果要描述中途各個位置的狀態,只有最後合計又不足夠。先寫清楚問題,再選擇函數,可以避免把輸出長度不同的結果當成同一類資料使用。

累積結果也不是原始觀測值的新版本。例子中的第二項 5,不代表第二個輸入原本是 5;第二個輸入仍是 3。這個 5 是前兩項 2 和 3 的合計。保留原始陣列與累積陣列各自的名稱,有助於之後解釋數據。

二維資料要說明沿哪個軸累積

考慮一個兩行三列的陣列。第一行是 2、3、1,第二行是 4、2、5。若使用 axis=1,計算會在每一行內沿列的位置前進。第一行的累積結果是 2、5、6;第二行則是 4、6、11。

np.cumsum(a, axis=1)

第二行由自己的第一項開始,不會接續第一行最後的累積結果。因此第二行第一個輸出是 4,而不是 10。這個細節說明,指定軸不只是改變顯示方向,也決定哪些元素屬於同一段累積計算。

如果使用 axis=0,計算會在每一列內沿行的位置前進。第一行輸出仍是 2、3、1,因為各列暫時只包含第一項。第二行輸出變為 6、5、6,分別來自同一列中的兩個輸入相加。

np.cumsum(a, axis=0)

這兩種結果都來自同一個輸入陣列,但意義不同。記錄結果時,應同時說明陣列的形狀和所用的軸。單獨寫出一組數值,往往不足以讓另一位讀者知道累積是怎樣進行的。

沒有指定軸時的行為

NumPy 文件說明,cumsum 的預設 axis 是 None,會對攤平後的陣列計算累積總和。在上述例子中,攤平序列依次是 2、3、1、4、2、5,輸出便是 2、5、6、10、12、17。

這個預設結果是一維序列,不能直接當成逐行獨立累積的二維結果。雖然輸入元素總數仍是六個,但輸出形狀與指定 axis 時不同。元素數目相同,不代表每個位置的語意也相同。

閱讀程式時,可以依次確認三件事:原始資料以甚麼順序排列、是否有指定軸、每個輸出位置累積了哪些輸入。這樣就能把函數名稱、陣列形狀和實際數字連在一起,而不只記住一個用法。

數值型別也是計算的一部分

文件亦指出,dtype 影響輸出與累加器使用的資料型別。因此,解讀數值結果不能只看公式,也要留意資料型別。本文使用的小整數例子,是為了清楚展示累積的順序與形狀,並不是對所有輸入型別作出同一種精度承諾。

對浮點數而言,cumsum 最後一項未必與 sum 的結果完全相等。文件解釋,sum 可能採用成對相加的方式,令捨入誤差表現不同。因此,不宜把小整數例子中的相等關係,直接推廣成所有數值計算都必然逐位相同。

Academia Master Trader 提供數據整理與數值方法的教育內容。歡迎瀏覽 academiamastertrader.com.br,認識更多主題並繼續學習。閱讀累積結果時,先確認順序、軸與資料型別,再說明每一個位置代表的合計。

Aprenda

NumPy count nonzero រាប់ធាតុដែលមិនសូន្យ មិនមែនបូកតម្លៃរបស់ធាតុទាំងនោះទេ

នៅពេលអានទិន្នន័យជាអារេ យើងអាចចង់ដឹងថា មានធាតុប៉ុន្មានដែលខុសពីសូន្យ។ សំណួរនេះខុសពីការសួរថា ផលបូកនៃតម្លៃទាំងអស់ស្មើប៉ុន្មាន។ អនុគមន៍ count_nonzero របស់ NumPy ឆ្លើយសំណួរអំពីចំនួនធាតុ មិនមែនអំពីផលបូកទេ។ ការបែងចែកន័យទាំងពីរនេះ ជួយឱ្យយើងពន្យល់លទ្ធផលបានច្បាស់។

សម្រាប់អារេដែលមានលេខធម្មតា តម្លៃសូន្យមិនត្រូវបានរាប់ទេ។ តម្លៃវិជ្ជមាននិងតម្លៃអវិជ្ជមានដែលខុសពីសូន្យ សុទ្ធតែត្រូវបានរាប់មួយដងសម្រាប់ធាតុនីមួយៗ។ ទំហំលេខមិនកំណត់ទម្ងន់ក្នុងការរាប់នេះទេ។ លេខពីរនិងលេខប្រាំពីរ រួមចំណែកមួយដូចគ្នា ព្រោះធាតុទាំងពីរខុសពីសូន្យ។

ឧទាហរណ៍មានធាតុប្រាំ

សន្មតថាអារេ a មានតម្លៃ 0, 5, 0, 2, 7 តាមលំដាប់។ មានធាតុសរុបប្រាំ ប៉ុន្តែមានតែធាតុបីដែលខុសពីសូន្យ គឺ 5, 2 និង 7។ ដូច្នេះលទ្ធផលនៃការរាប់គឺ 3។ លទ្ធផលនេះមិនមែនជា 14 ដែលជាផលបូកនៃតម្លៃទាំងអស់នោះទេ។

np.count_nonzero(a)

ការហៅខាងលើផ្តល់ចំនួនធាតុដែលត្រូវបានរាប់។ វាមិនផ្តល់បញ្ជីតម្លៃទាំងនោះ ហើយក៏មិនផ្តល់ទីតាំងរបស់វាដែរ។ មុននឹងប្រើលទ្ធផល យើងគួរសរសេរអត្ថន័យរបស់លេខនោះជាពាក្យសាមញ្ញថា ចំនួនធាតុដែលមិនសូន្យក្នុងអារេនេះ។

រូបពន្យល់ផ្ទាល់ខ្លួន៖ អារេមានតម្លៃ 0, 5, 0, 2, 7។ មានធាតុមិនសូន្យបី។ លទ្ធផល count_nonzero គឺ 3។

រូបនេះបង្ហាញធាតុទាំងប្រាំដោយឡែកពីលទ្ធផលរាប់។ ប្រអប់ដែលមានតម្លៃខុសពីសូន្យត្រូវបានសម្គាល់ ដើម្បីឱ្យឃើញថា អ្វីដែលកំពុងត្រូវបានរាប់គឺធាតុ មិនមែនចំនួនឯកតាដែលតម្លៃនីមួយៗតំណាងឱ្យទេ។ យើងទទួលបាន 3 ព្រោះមានប្រអប់បីដែលបំពេញលក្ខខណ្ឌ។

ចំនួនសរុបមិនស្មើនឹងចំនួនមិនសូន្យ

ចំនួនធាតុសរុបរបស់អារេ និងចំនួនធាតុដែលមិនសូន្យ អាចខុសគ្នា។ ក្នុងឧទាហរណ៍នេះ ទំហំអារេគឺប្រាំ ខណៈចំនួនធាតុមិនសូន្យគឺបី។ ការរាយការណ៍លេខណាមួយដោយគ្មានឈ្មោះពណ៌នា អាចធ្វើឱ្យអ្នកអានច្រឡំរវាងទំហំទិន្នន័យនិងចំនួនដែលត្រូវបានរាប់។

ប្រសិនបើអារេមានតែសូន្យទាំងអស់ ចំនួនធាតុមិនសូន្យគឺសូន្យ។ ប្រសិនបើធាតុទាំងអស់ខុសពីសូន្យ ចំនួនដែលរាប់បានស្មើនឹងចំនួនធាតុសរុប។ នេះជាការអានអត្ថន័យនៃលទ្ធផល មិនមែនជាការវាស់ទំហំតម្លៃនៅក្នុងអារេទេ។

ឧទាហរណ៍ តម្លៃអវិជ្ជមានមួយដែលខុសពីសូន្យ ក៏ត្រូវបានរាប់ដែរ។ ដូច្នេះ count_nonzero មិនស្មើនឹងការរាប់តែតម្លៃវិជ្ជមានទេ។ ឈ្មោះរបស់អនុគមន៍ប្រាប់ថា វារាប់អ្វីដែលមិនសូន្យ ហើយមិនបានដាក់លក្ខខណ្ឌថាត្រូវធំជាងសូន្យឡើយ។

អ័ក្សកំណត់ក្រុមដែលត្រូវរាប់

ឥឡូវគិតពីតារាងពីរជួរដេកនិងបីជួរឈរ។ ជួរដេកទីមួយមាន 0, 5, 0 ហើយជួរដេកទីពីរមាន 2, 0, 7។ នៅពេលមិនកំណត់អ័ក្ស អនុគមន៍រាប់ធាតុមិនសូន្យក្នុងតារាងទាំងមូល ហើយលទ្ធផលគឺ 3។

នៅពេលកំណត់ axis=1 ការរាប់ធ្វើឡើងក្នុងជួរដេកនីមួយៗ។ ជួរដេកទីមួយមានធាតុមិនសូន្យមួយ ហើយជួរដេកទីពីរមានពីរ។ ដូច្នេះលទ្ធផលគឺអារេដែលមានចំនួន 1 និង 2។ ចំនួនទាំងនេះតំណាងឱ្យជួរដេកពីរផ្សេងគ្នា។

np.count_nonzero(a, axis=1)

នៅពេលកំណត់ axis=0 ការរាប់ធ្វើឡើងតាមជួរដេកនៅក្នុងជួរឈរនីមួយៗ។ ជួរឈរទាំងបីមានធាតុមិនសូន្យមួយដូចគ្នា។ ដូច្នេះលទ្ធផលមានចំនួន 1, 1, 1។ ទិន្នន័យដើមនៅដដែល ប៉ុន្តែក្រុមដែលត្រូវរាប់បានផ្លាស់ប្តូរ។

np.count_nonzero(a, axis=0)

ការសរសេរអ័ក្សជាមួយលទ្ធផលមានសារៈសំខាន់សម្រាប់ការពន្យល់។ អារេដែលមានលេខបីមិនអាចប្រាប់ដោយខ្លួនឯងថា លេខទាំងនោះជាចំនួនសម្រាប់ជួរឈរ ឬជួរដេកឡើយ។ បរិបទនៃការហៅអនុគមន៍ជួយកំណត់ន័យនោះ។

រាប់ចំនួន និងរកកូអរដោនេ

ឯកសារ NumPy បែងចែក count_nonzero ពី nonzero។ អនុគមន៍ទីមួយផ្តល់ចំនួន ខណៈអនុគមន៍ទីពីរផ្តល់កូអរដោនេរបស់ធាតុដែលមិនសូន្យ។ ការជ្រើសរើសអាស្រ័យលើសំណួរដែលយើងត្រូវឆ្លើយ។ ប្រសិនបើត្រូវការដឹងថាប៉ុន្មាន ការរាប់គឺសមស្រប។ ប្រសិនបើត្រូវការដឹងថានៅឯណា ត្រូវអានលទ្ធផលជាទីតាំង។

ជម្រើស keepdims=True រក្សាអ័ក្សដែលត្រូវបានរាប់ឱ្យនៅក្នុងទម្រង់លទ្ធផល ដោយមានប្រវែងមួយ។ សម្រាប់តារាងពីរជួរដេក ការរាប់តាម axis=1 នឹងរក្សាលទ្ធផលជាទម្រង់ពីរជួរនិងមួយជួរឈរ។ ចំនួននៅតែជា 1 និង 2 ប៉ុន្តែទម្រង់អារេខុសពីលទ្ធផលលំនាំដើម។

ឯកសារក៏ពន្យល់ថា ន័យទូទៅនៃការរាប់ពឹងលើការបកស្រាយធាតុក្នុងបរិបទប៊ូលីន។ សម្រាប់អត្ថបទនេះ យើងប្រើតែលេខធម្មតាដើម្បីរក្សាឧទាហរណ៍ឱ្យច្បាស់។ នៅពេលផ្លាស់ប្តូរប្រភេទទិន្នន័យ ត្រូវអាននិយមន័យរបស់ធាតុជាមុន មិនត្រូវសន្មតថាអារេគ្រប់ប្រភេទមានន័យដូចលេខទាំងនេះទេ។

Academia Master Trader ផ្តល់មាតិកាអប់រំអំពីការរៀបចំទិន្នន័យនិងវិធីសាស្ត្រលេខ។ សូមចូលទៅកាន់ academiamastertrader.com.br ដើម្បីស្គាល់ប្រធានបទផ្សេងទៀតនិងបន្តការសិក្សា។ ចាប់ផ្តើមពីសំណួរច្បាស់លាស់៖ តើត្រូវការចំនួន តម្លៃ ឬទីតាំង? បន្ទាប់មកអានលទ្ធផលជាមួយអ័ក្សនិងទម្រង់អារេ។

Aprenda

الدالة argmin في NumPy تحدد فهرس أصغر قيمة، والمحور يحدد معنى الفهرس

عند قراءة جدول عددي، قد نريد معرفة أصغر مقدار فيه، أو تحديد موضع هذا المقدار داخل البيانات الأصلية. السؤال الأول يتعلق بالقيمة، أما الثاني فيتعلق بالفهرس. تعيد الدالة argmin في NumPy الفهارس التي تشير إلى القيم الصغرى، ولا تعيد تلك القيم نفسها.

يساعد هذا التمييز على تنظيم خطوات التحليل. يمكن أن نستعمل الفهرس للوصول إلى عنصر في مصفوفة، لكن الرقم الناتج لا يحمل تلقائيا وحدة القياس الخاصة بالبيانات. إذا كانت المدخلات أطوالا، فلا يصبح الفهرس طولا. إنه وصف للمكان داخل بنية محددة.

مثال يميز الموضع عن المقدار

لنفترض أن المصفوفة a تحتوي الأعداد 8 و3 و6 و5 بهذا الترتيب. أصغر قيمة هي 3. تقع هذه القيمة في الموضع الثاني عند العد المعتاد، لكن فهرسها البرمجي هو 1 لأن الفهرسة تبدأ من الصفر.

يعيد الاستدعاء التالي العدد 1:

np.argmin(a)

لا تعني هذه الإجابة أن أصغر قيمة تساوي واحدا. إنها تعني أن أصغر قيمة توجد عند الفهرس 1. وإذا قرأنا العنصر الموجود في ذلك الموضع من المصفوفة الأحادية البعد، فستكون القيمة المقروءة هي 3.

توضيح أصلي للدالة argmin: القيم 8 و3 و6 و5، والفهارس 0 و1 و2 و3. أصغر قيمة هي 3، بينما الفهرس الناتج هو 1.

يضع الشكل الفهارس في صف مستقل عن القيم. الفصل البصري بينهما يجعل قراءة النتيجة أوضح: العدد 1 يشير إلى مكان، والعدد 3 هو محتوى ذلك المكان. لا يتغير ترتيب الإدخال لمجرد حساب الفهرس.

صياغة السؤال قبل اختيار الدالة

تفرق وثائق NumPy بين argmin التي تعيد فهارس القيم الصغرى، وamin التي تعيد القيمة الصغرى. لذلك يبدأ الاختيار من المعلومة المطلوبة. إذا كان العرض يحتاج إلى أصغر مقدار، فإن الفهرس وحده لا يكفي للإجابة عن السؤال.

أما إذا احتجنا إلى الوصول إلى العنصر الأصلي، فإن الفهرس قد يكون الخطوة المناسبة. في مثال المصفوفة الأحادية البعد يمكن حفظ الناتج في متغير p، ثم قراءة العنصر a[p]. هنا يمثل p عنوان الموضع، بينما يمثل العنصر المقروء قيمة البيانات.

من المفيد تسمية المتغيرات بحسب معناها. اسم يدل على الفهرس يختلف عن اسم يدل على القيمة الصغرى. هذا يجعل شرح الشيفرة أسهل، خصوصا عندما تتشابه الأعداد أو يكون الفهرس نفسه موجودا أيضا ضمن قيم الإدخال.

عند تكرار أصغر قيمة

لنغير القيم إلى 8 و3 و6 و3. تظهر القيمة الصغرى مرتين، عند الفهرسين 1 و3. تنص وثائق argmin على إعادة الفهرس الموافق لأول ظهور للقيمة الصغرى. لذلك تكون الإجابة هنا 1.

هذه النتيجة ليست قائمة بكل مواضع القيمة الصغرى. كما أنها ليست عدد مرات تكرارها. إنها فهرس واحد يوافق أول ظهور ضمن البحث الذي ينفذه الاستدعاء. إذا كان السؤال مختلفا، فلا ينبغي تفسير هذا الفهرس وكأنه جواب عن جميع الأسئلة المتعلقة بالتكرار.

قبل عرض الناتج، من المفيد كتابة وصف قصير له: فهرس أول قيمة صغرى في الإدخال المحدد. يربط هذا الوصف الرقم بمعناه، ويمنع الخلط بين الموضع والتكرار والمقدار.

المحور يحدد مجموعة المقارنة

لنتناول مصفوفة من صفين وثلاثة أعمدة. يحتوي الصف الأول الأعداد 8 و3 و6، ويحتوي الصف الثاني الأعداد 4 و7 و2. عند البحث عبر أعمدة كل صف، نحصل على فهرس مستقل لذلك الصف.

يعيد الاستدعاء التالي الفهرسين 1 و2:

np.argmin(a, axis=1)

في الصف الأول تشير النتيجة 1 إلى العمود الذي يحتوي العدد 3. وفي الصف الثاني تشير النتيجة 2 إلى العمود الذي يحتوي العدد 2. هذان فهرسا عمود داخل كل صف، وليسا القيمتين الصغريين نفسيهما.

أما عند البحث عبر الصفوف داخل كل عمود، فتختلف المقارنة. في العمود الأول يكون العدد 4 أصغر من 8، وفي الثاني يكون 3 أصغر من 7، وفي الثالث يكون 2 أصغر من 6. لذلك تكون النتيجة هي فهارس الصفوف 1 و0 و1.

np.argmin(a, axis=0)

رقم الفهرس لا يكتمل معناه دون معرفة المحور. يجب أن يبين الشرح هل يشير الناتج إلى صف داخل عمود، أم إلى عمود داخل صف. تبقى البيانات نفسها، لكن مجموعات المقارنة تتغير مع اختيار المحور.

البحث الافتراضي وشكل النتيجة

عندما لا نحدد المحور، تتعامل الدالة افتراضيا مع فهرس في المصفوفة بعد تسطيحها. في مثال الصفين السابق تكون أصغر قيمة هي 2، وفهرسها في التسلسل المسطح هو 5. لا تمثل هذه النتيجة فهرس عمود بمفرده.

يوضح هذا المثال الفرق بين بحث شامل وبحث مستقل لكل صف. قد نبدأ من الجدول نفسه، لكن نوع الفهرس وعدد النتائج يعتمدان على الاستدعاء. من الأفضل تسجيل المحور مع النتيجة بدلا من عرض رقم منفصل عن سياقه.

يوجد أيضا الخيار keepdims. عندما تكون قيمته True، يبقى المحور الذي جرى اختزاله في شكل النتيجة بطول واحد. هذا يتعلق بشكل مصفوفة الفهارس، ولا يحول الفهارس إلى قيم صغرى. يفيد الفصل بين الشكل والمحتوى في متابعة العمليات اللاحقة بوضوح.

تقدم Academia Master Trader مواد تعليمية عن تنظيم البيانات والطرق العددية. زر academiamastertrader.com.br للتعرف إلى موضوعات أخرى ومواصلة التعلم. ابدأ بالسؤال الذي تريد الإجابة عنه: ما أصغر قيمة، أم أين توجد؟ ثم اقرأ الناتج مع شكل المصفوفة والمحور المستخدم.

Aprenda

الدالة argmax في NumPy تعيد موضع القيمة العظمى، وليس القيمة نفسها

عندما نبحث عن أكبر عدد في مجموعة بيانات، قد نحتاج إلى العدد نفسه، وقد نحتاج إلى معرفة مكانه. هذان سؤالان مختلفان. تجيب الدالة argmax في NumPy عن سؤال الموضع: فهي تعيد الفهرس الذي يشير إلى القيمة العظمى، بدلا من إعادة تلك القيمة مباشرة.

يساعد الفصل بين الفهرس والقيمة على قراءة النتائج بصورة صحيحة. إذا كانت النتيجة هي العدد اثنان، فلا يعني ذلك بالضرورة أن أكبر قيمة في البيانات تساوي اثنين. قد يعني أن أكبر قيمة تقع في الموضع ذي الفهرس اثنين. لذلك ينبغي تحديد معنى الناتج قبل استخدامه في خطوة أخرى.

مثال بسيط بأربعة أعداد

لنفترض أن المصفوفة a تحتوي القيم 4 و9 و2 و7 بهذا الترتيب. فهارس هذه المواضع هي 0 و1 و2 و3. تبدأ الفهرسة من الصفر، ولذلك تقع القيمة 4 في الفهرس 0، وتقع القيمة 9 في الفهرس 1.

عند تنفيذ الاستدعاء التالي تكون النتيجة هي 1:

np.argmax(a)

السبب هو أن أكبر قيمة، وهي 9، تقع في الفهرس 1. لا تعني النتيجة أن أكبر عدد يساوي واحدا. إنها عنوان موضع داخل المصفوفة. أما إذا قرأنا العنصر الموجود في ذلك الموضع، فسنحصل على القيمة 9.

توضيح للدالة argmax: قيم الإدخال هي 4 و9 و2 و7، وفهارسها 0 و1 و2 و3. أكبر قيمة هي 9، لكن الفهرس الذي تعيده الدالة هو 1.

يفصل الشكل بين صف الفهارس وصف القيم، ثم يوضح الفهرس الناتج والقيمة التي يشير إليها. هذا الفصل هو الفكرة الأساسية للمثال. عدد المواضع وأرقام الفهارس ليسا بديلا عن الأعداد المخزنة في تلك المواضع.

كيف نقرأ النتيجة خطوة بخطوة

نبدأ بمقارنة القيم الأربع في المثال. العدد 9 هو الأكبر بينها. بعد ذلك نحدد موقعه في الإدخال الأصلي. يوجد في الموضع الثاني عند العد بالكلمات، لكن فهرسه هو 1 لأن الترقيم البرمجي يبدأ من الصفر.

قد تبدو عبارة الموضع الثاني والفهرس واحد متناقضة في البداية، لكنها تصف المكان نفسه بطريقتين مختلفتين. من الأفضل استعمال كلمة فهرس عند شرح الناتج البرمجي، وكتابة سلسلة الفهارس إلى جانب القيم عندما يكون المثال تعليميا.

إذا حفظنا الفهرس الناتج في متغير اسمه p، فإن قراءة العنصر a[p] في مصفوفة أحادية البعد تعطينا القيمة الموجودة في ذلك الفهرس. المتغير p يمثل موضعا، بينما العنصر المقروء يمثل بيانات. لا ينبغي التعامل معهما كأنهما الكمية نفسها.

الفرق بين أكبر قيمة وموضعها

تصف وثائق NumPy الدالة amax بأنها تعيد القيمة العظمى، بينما تعيد argmax فهارس القيم العظمى. في مثالنا، القيمة المطلوبة عند السؤال عن المقدار هي 9. أما الجواب عن سؤال المكان فهو الفهرس 1.

اختيار الدالة يبدأ من صياغة السؤال. إذا كان التقرير يحتاج إلى أكبر قيمة، فإن عرض الفهرس وحده لا يجيب عنه. وإذا كنا نحتاج إلى الوصول إلى العنصر الأصلي، فقد يكون الفهرس هو المعلومة المناسبة للخطوة التالية.

لا يمثل الفهرس قياسا جديدا للظاهرة التي ندرسها. فهو لا يحمل وحدة السعر أو الزمن أو المسافة لمجرد أن عناصر المصفوفة تحمل إحدى هذه الوحدات. معناه هنا هو الموقع داخل بنية البيانات.

ما الذي يحدث عند تكرار القيمة العظمى

لنغير الإدخال إلى القيم 4 و9 و2 و9. توجد الآن أكبر قيمة مرتين. تنص وثائق الدالة على إعادة الفهرس الموافق لأول ظهور للقيمة العظمى. لذلك تكون النتيجة 1، لا 3، ولا قائمة تضم الموضعين.

هذه قاعدة محددة ينبغي تذكرها عند تفسير الناتج. ظهور فهرس واحد لا يثبت أن القيمة العظمى ظهرت مرة واحدة فقط. قد توجد مواضع أخرى تحمل القيمة نفسها، لكن هذا الاستدعاء يعيد أول ظهور بحسب ترتيب البحث المعني.

إذا كانت المهمة تتطلب جميع المواضع التي تحمل القيمة العظمى، فإن ذلك مطلب مختلف عن الحصول على أول فهرس. ينبغي وصف هذا المطلب صراحة بدلا من افتراض أن argmax تعيد قائمة بكل حالات التعادل.

المحور يحدد معنى الفهرس في المصفوفات متعددة الأبعاد

لنفترض مصفوفة ذات صفين وثلاثة أعمدة. يحتوي الصف الأول القيم 4 و9 و2، ويحتوي الصف الثاني القيم 7 و1 و8. عند تحديد axis=1 نبحث داخل كل صف، فتكون الفهارس الناتجة 1 و2.

الفهرس 1 في النتيجة الأولى يشير إلى العمود الذي يحتوي القيمة 9 في الصف الأول. والفهرس 2 في النتيجة الثانية يشير إلى العمود الذي يحتوي القيمة 8 في الصف الثاني. هذه فهارس على امتداد محور الأعمدة داخل كل صف، وليست قيما عظمى بحد ذاتها.

أما عند تحديد axis=0 فنبحث على امتداد الصفوف داخل كل عمود. في المثال تكون النتيجة 1 و0 و1. يوضح هذا الاختلاف أن رقم الفهرس لا يمكن فهمه من دون معرفة المحور الذي جرى البحث عليه.

الإعداد الافتراضي يختلف عن البحث صفا صفا

القيمة الافتراضية للمحور هي None. في هذه الحالة يكون الفهرس بالنسبة إلى المصفوفة بعد تسطيحها، وليس تلقائيا بالنسبة إلى أعمدة كل صف. في مصفوفتنا السابقة، أكبر قيمة هي 9، وفهرسها في التسلسل المسطح هو 1.

هذا المثال يعطي الرقم نفسه الذي ظهر في بحث الصف الأول، لكن التطابق العددي لا يجعل المعنيين متساويين. في حالة نبحث في الإدخال كله، وفي الحالة الأخرى نحصل على نتيجة مستقلة لكل صف. يجب تسجيل المحور إلى جانب النتيجة لكي يبقى معناها واضحا.

تقدم Academia Master Trader مواد تعليمية عن الطرق العددية وتنظيم البيانات. زر academiamastertrader.com.br للتعرف إلى موضوعات أخرى ومواصلة التعلم. ابدأ بتحديد ما إذا كنت تحتاج إلى القيمة أم إلى موضعها، ثم اقرأ الفهرس في سياق شكل المصفوفة والمحور المستخدم.

Aprenda