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 concatenate réunit des tableaux le long d'un axe existant en respectant leurs dimensions compatibles

Réunir deux tableaux numériques demande de préciser la direction de l'assemblage. NumPy concatenate joint une séquence de tableaux le long d'un axe existant. Les dimensions doivent correspondre, sauf celle qui porte l'assemblage. Cette règle explique la forme du résultat avant même de regarder ses valeurs.

Academia Master Trader propose cette explication en français aux lecteurs du Sénégal. Les exemples concernent uniquement la structure des tableaux numériques. Ils ne représentent ni des cours de marché, ni des signaux, ni des résultats financiers. Deux petits tableaux permettent de suivre chaque entrée.

Commencer par deux tableaux compatibles

Prenons un tableau a dont les lignes sont [1,2] et [3,4]. Sa forme est (2,2). Prenons ensuite un tableau b contenant une seule ligne, [5,6], de forme (1,2).

L'appel np.concatenate((a,b),axis=0) produit les lignes [1,2], [3,4] et [5,6]. La forme du résultat est (3,2). Les deux colonnes sont conservées et les nombres de lignes s'additionnent.

Schéma original : NumPy concatenate réunit un tableau de deux lignes et deux colonnes et un tableau d'une ligne et deux colonnes sur l'axe zéro ; le résultat possède trois lignes et deux colonnes.

L'axe zéro existe déjà dans les tableaux de départ. L'opération allonge cet axe. Elle n'ajoute pas automatiquement une nouvelle dimension au résultat.

Lire la dimension qui peut changer

Pour un assemblage sur l'axe zéro, la première dimension peut différer entre les entrées. Ici, elle vaut deux pour a et un pour b. La seconde dimension vaut deux dans les deux tableaux.

Cette égalité des autres dimensions rend l'assemblage possible. On peut ajouter la ligne de b après les lignes de a sans devoir inventer une troisième colonne ni compléter une ligne incomplète.

Écrire les formes côte à côte donne une vérification claire : (2,2) et (1,2) deviennent (3,2) sur l'axe zéro. Le changement concerne la longueur de l'axe choisi, pas le nombre d'axes.

Le choix de l'axe change la compatibilité

Les mêmes formes ne sont pas nécessairement compatibles pour tous les axes. Un assemblage sur l'axe un conserve la première dimension et réunit les entrées dans la seconde dimension.

Avec a de forme (2,2) et b de forme (1,2), les premières dimensions ne correspondent pas. On ne peut donc pas simplement demander le même assemblage sur l'axe un en supposant que NumPy adaptera les lignes.

La fonction ne promet pas de compléter les dimensions manquantes. Il faut choisir des tableaux dont les dimensions autres que celle de l'assemblage sont compatibles avec la règle documentée.

Une transposition permet un autre exemple

La référence utilise b.T pour présenter un assemblage sur l'axe un. Ce tableau transposé a la forme (2,1), avec les valeurs cinq et six dans une colonne.

L'appel np.concatenate((a,b.T),axis=1) donne les lignes [1,2,5] et [3,4,6]. La forme du résultat est (2,3).

La première dimension vaut maintenant deux pour les deux entrées. La seconde dimension, celle de l'assemblage, passe de deux plus un à trois. La transposition et la concaténation restent deux opérations distinctes dans cette explication.

Un axe existant n'est pas un axe nouveau

La référence distingue concatenate de stack. Concatenate réunit les tableaux sur un axe existant, tandis que stack assemble une séquence le long d'un nouvel axe.

Dans le premier exemple, le résultat reste bidimensionnel. Il possède davantage de lignes, mais sa forme contient toujours deux dimensions. Trois lignes ne signifient pas trois dimensions.

Garder cette distinction évite de confondre la longueur d'un axe avec le nombre d'axes. Une forme (3,2) décrit deux dimensions, dont la première a une longueur de trois.

L'ordre des entrées compte

Dans np.concatenate((a,b),axis=0), a précède b dans la séquence fournie. Les lignes de a sont donc suivies de celle de b dans l'exemple.

La fonction ne trie pas les valeurs par ordre numérique. Si les valeurs de b étaient plus petites, leur position dans la séquence d'entrée resterait la raison de leur place dans l'assemblage.

Décrire l'ordre des tableaux est donc aussi utile que décrire l'axe. L'axe indique la direction de l'assemblage ; la séquence indique quel tableau vient avant l'autre.

Le cas axis égal à None a une règle différente

La référence indique que les tableaux sont aplatis avant utilisation lorsque axis vaut None. Avec a et b de notre exemple, np.concatenate((a,b),axis=None) produit [1,2,3,4,5,6].

Ce résultat est unidimensionnel. Il ne conserve pas la séparation initiale en lignes et colonnes. Cette règle doit être présentée explicitement, plutôt que comme un simple autre numéro d'axe.

Le choix None ne désigne pas un axe existant. Il demande un traitement particulier avant l'assemblage. Pour expliquer le résultat, montrer la séquence complète est plus clair qu'indiquer seulement le nombre total d'entrées.

Conserver les limites de l'exemple numérique

Cette leçon utilise des tableaux numériques ordinaires. La référence précise que concatenate ne préserve pas les masques des entrées MaskedArray et renvoie vers la fonction dédiée du module des tableaux masqués lorsque cette propriété doit être conservée.

Il ne faut donc pas transformer le présent exemple en promesse générale de préserver toutes les propriétés de tous les types de tableaux. Les formes, les valeurs et les propriétés particulières méritent des vérifications séparées.

Poursuivez votre apprentissage avec Academia Master Trader sur academiamastertrader.com.br. Aprenda donne accès aux ressources pédagogiques. Notez les formes de départ, choisissez l'axe, comparez les autres dimensions et décrivez la forme obtenue. Cette méthode distingue un assemblage de tableaux d'un tri, d'une addition de valeurs ou de l'insertion d'un nouvel axe.

NumPy ndarray flatten returns a one-dimensional copy with entries arranged in a chosen order

Reducing an array to one dimension and deciding whether the result is a copy are separate questions. The NumPy ndarray method flatten answers both: it returns a copy of the input array collapsed into one dimension. Its order argument specifies how the entries are arranged in that copy.

Academia Master Trader presents this explanation in English for readers in the Federated States of Micronesia. The examples concern numerical array structure only. They are not market prices, trading signals or financial results. A two-by-two array gives a clear starting point.

Begin with a two-dimensional numerical array

Let a be a NumPy array with rows [1,2] and [3,4]. Its shape is (2,2), meaning two axes, each of length two. The array contains four numerical entries.

The call a.flatten() returns [1,2,3,4] as a one-dimensional array. Its shape is (4,). By default, flatten uses C-style order, which reads this example across each row before moving to the next row.

Original diagram: NumPy flatten reads a two-by-two numerical array with rows one two and three four into a one-dimensional copy containing one two three four, using default C order.

The method does not add the four values together. The output still contains four entries. It changes their arrangement into one dimension and returns a copy.

The method is called on the array

The documented interface is an ndarray method. In the expression a.flatten(), a is the array whose entries are being flattened.

That call structure is worth keeping clear when recording an example. The method name follows the array, and its optional argument selects the order. The input array is not written as another ordinary positional argument inside this method call.

For this lesson, the relevant object is a NumPy numerical array. Establishing the input type keeps the explanation tied to the interface described in the reference rather than assuming every Python sequence has this method.

C order reads across the rows in this example

For rows [1,2] and [3,4], default C order gives one and two from the first row, then three and four from the second row.

The shape (4,) describes the resulting one-dimensional arrangement. It does not record which reading order produced that sequence, so include the order when the sequence matters.

The ascending output follows from the chosen values and their positions. Flatten is not a numerical sorting method. Another input could give an irregular sequence while following the same row-major rule.

F order reads down the columns

The call a.flatten('F') returns [1,3,2,4] for the same input. The reference describes F as column-major, Fortran-style order.

The reading sequence takes one and three from the first column, followed by two and four from the second column. The result still has shape (4,) and still contains the same four values.

This contrast shows why shape alone does not explain the output contents. Both orders produce a one-dimensional copy, but the values appear at different positions in that copy.

A copy is part of the documented result

The reference explicitly describes flatten as returning a copy. A beginner explanation should retain that point rather than treating flatten and every other shape operation as interchangeable.

For the ordinary numerical array in this lesson, assigning a different number to an entry in the returned copy does not replace the corresponding numerical entry in the original array. The result is a copy, not another shape-only view of the same numerical buffer.

Keep that statement scoped to the numerical example. It is not a claim about recursively duplicating arbitrary Python objects that might be stored in a different kind of array.

Do not infer storage behaviour from brackets

The change from two rows to one flat sequence is visible in the printed array. That visual change alone does not establish whether an operation returns a copy or a view.

Here the copy property comes from the method's documented contract. The brackets explain the dimensional arrangement, while the reference explains the returned storage relationship.

This separation is useful when comparing array operations. Two methods may display the same values and shape while giving different guarantees about copying. Read both properties rather than substituting one for the other.

The order argument has other documented choices

The reference also lists A and K. A uses column-major order when the input is Fortran contiguous in memory, and row-major order otherwise. Its meaning therefore includes a condition about the input's layout.

K flattens in the order the elements occur in memory. That is a different description from simply choosing the visible row or column sequence in every situation.

For a first example, C and F give direct, readable sequences. When introducing A or K, preserve the documented layout conditions instead of predicting their results from a printed grid alone.

Entry count and dimension count answer different questions

The input shape (2,2) describes four entries across two dimensions. The output shape (4,) describes four entries in one dimension. Flattening reduces the number of dimensions here without reducing the number of entries.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the array, state the reading order and write the complete sequence for a small example. Then keep the documented copy property separate from the shape change and from any assumption that values were sorted or combined.

NumPy ravel produces a one-dimensional array by reading entries in a specified index order

Flattening an array requires more than stating that the output has one dimension. The entries also need an order. NumPy ravel returns a contiguous one-dimensional array containing the input's elements. Its order argument determines how those elements are read before being packed into the result.

Academia Master Trader presents this explanation in English for readers in the Marshall Islands. The examples concern array structure only. They are not market prices, trading signals or financial results. A small two-row array makes the difference between the two main index orders visible.

Begin with two rows and three columns

Let x be a NumPy array with rows [1,2,3] and [4,5,6]. Its shape is (2,3), so it contains six entries arranged along two axes.

The call np.ravel(x) produces [1,2,3,4,5,6]. The result has shape (6,). The default order is C-style indexing, which reads this example across each row before continuing to the next row.

Original diagram: A two-row array with rows one two three and four five six is flattened by NumPy ravel in C order to one two three four five six, or in F order to one four two five three six.

The output retains six entries. Ravel does not combine them into a total or average. It places them in a one-dimensional arrangement using the selected reading order.

C order changes the last axis index fastest

In the two-dimensional example, the column index changes fastest under C order. The row index changes more slowly. This gives one, two and three from the first row, followed by four, five and six from the second row.

The same description extends to more dimensions: the last axis index changes fastest, and the first changes slowest. The rule concerns the sequence of index positions used to read the array.

This is more precise than saying that C order always follows physical memory. The documentation explicitly separates C-style indexing from the underlying memory layout of the input array.

F order changes the first axis index fastest

The call np.ravel(x,order='F') produces [1,4,2,5,3,6]. In this example, the first axis is the row axis, so its index changes fastest.

The reading sequence takes one and four from the first column, then two and five from the second column, then three and six from the third column. The result still has shape (6,).

Changing the order argument changes the sequence, not the number of entries. Both outputs contain the original values, but their positions in the one-dimensional result differ.

Index order is not numerical sorting

The F-order result is not ascending, but that does not make it disordered relative to the function's rule. It follows a different sequence of array indices.

Likewise, the ascending C-order example is a consequence of the chosen input values. Ravel does not sort values from small to large. Another input could produce an irregular numerical sequence while following the same C-order indexing rule.

When explaining an output, identify the reading path through the input rather than attributing the arrangement to the magnitudes of the numbers. Index positions explain the result.

C and F do not inspect the input layout to choose their rule

The documentation says that the C and F options refer only to axis indexing order. They take no account of the underlying memory layout when selecting that index sequence.

An input's printed rows therefore do not justify a claim about how all of its data are stored. The order argument tells ravel how to read indices for the requested output.

Keep those ideas separate: the input has a shape, its storage has a layout and the operation has a reading order. They can be related without being interchangeable descriptions.

A order chooses from the input's contiguous layout

The order argument also accepts A. The reference defines A as Fortran-like index order when the input is Fortran contiguous in memory, and C-like order otherwise.

That is a conditional rule, so it should not be described as always matching the visible row sequence. The input's layout is part of the condition.

For a beginner explanation, C and F give direct index-order examples. Introduce A with its documented condition rather than guessing its result from a picture of the values alone.

A one-dimensional result can require a copy

The reference describes the output as a contiguous flattened array and states that a copy is made only if needed. Ravel should therefore not be described as always returning a view.

It should not be described as always making an independent copy either. Whether a copy is needed belongs to the input and the requested arrangement, not simply to the fact that the result has one dimension.

A different bracket layout is not proof of independent storage. If later work needs an independent snapshot, that requirement must be handled separately from the explanation of flattening.

State the shape and the reading order together

For the two-row example, both C and F orders yield shape (6,). Shape alone cannot distinguish [1,2,3,4,5,6] from [1,4,2,5,3,6].

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Record the input shape, identify the requested reading order and write the complete output sequence for a small example. That keeps flattening distinct from sorting, aggregating values and assuming an independent copy.

NumPy atleast_3d gives arrays a minimum of three dimensions with specific positions for added size-one axes

A one-dimensional vector and a two-dimensional table need different shape changes to become three-dimensional. NumPy atleast_3d handles these inputs according to their starting dimensions. The operation provides a minimum of three dimensions, rather than forcing every input into one fixed three-dimensional shape.

Academia Master Trader presents this explanation in English for readers in Palau. The examples concern numerical array structure only. They are not prices, trading signals or financial results. Following the shape entries makes the added dimensions easier to understand.

A vector gains a leading and a trailing dimension

The reference states that a one-dimensional array with shape (N,) becomes a view with shape (1,N,1). The original length stays in the middle position, between two new dimensions of length one.

For a NumPy array x containing [0.,1.,2.], the input shape is (3,). Calling np.atleast_3d(x) gives shape (1,3,1).

Original diagram: NumPy atleast_3d changes vector shape three into shape one by three by one, keeping the original length three in the middle and adding size-one dimensions at the beginning and end.

The three numerical entries remain. The two new ones in the shape are dimension lengths, not extra values inserted into the vector. Shape and array contents describe different properties.

A two-dimensional array gains a trailing dimension

For a two-dimensional input with shape (M,N), the documented output shape is (M,N,1). The two existing dimension lengths keep their order, and a new trailing dimension has length one.

The reference gives an input reshaped to (4,3). Its atleast_3d result has shape (4,3,1). The new axis is at the end, not at the beginning.

State the full result shape when explaining this operation. Saying that one dimension is added does not identify where it appears. The distinction between (1,4,3) and (4,3,1) is structural, even though both shapes describe twelve entries.

The operation does not add every new axis at the front

The vector rule and the two-dimensional rule are different. A vector becomes (1,N,1), while a two-dimensional array becomes (M,N,1).

A description that always adds leading size-one axes would therefore give the wrong output shape. Read the documented rule for the starting dimension count instead of assuming a single insertion pattern.

For the three-entry vector, writing (1,1,3) would place the original length in the last position. That is not the vector rule described by atleast_3d, which places it in the middle.

A scalar becomes a one-by-one-by-one array

The reference shows np.atleast_3d(3.0) returning an array containing [[[3.]]]. The result has shape (1,1,1) and contains one numerical entry.

The three dimensions each have length one. Multiplying those lengths gives one, so the additional dimensions do not create more copies of the number.

This example separates dimension count from entry count. The result has three dimensions but one entry. A vector example can have three dimensions and three entries. Neither dimension count alone nor bracket depth alone tells the whole story.

Arrays already meeting the minimum are preserved

The documentation states that arrays with three or more dimensions are preserved. An array that already has shape (1,1,2) meets the minimum without adding a new axis.

The function also does not reduce an array with more than three dimensions to exactly three. The word at least expresses a lower bound, not an instruction to flatten higher-dimensional structure.

Before predicting a change, identify the input's number of dimensions. If the array already meets the minimum, do not describe an extra leading or trailing axis as a required part of the operation.

Similar contents can begin with different shapes

The reference compares the separate inputs [1,2], [[1,2]] and [[[1,2]]]. Each contains the same two numerical values, but their starting dimensions differ.

The first two inputs yield results with shape (1,2,1). The third input already has three dimensions and retains shape (1,1,2).

This is a useful reason to record shape before discussing values. Matching contents do not guarantee matching shapes after a minimum-dimension operation. The original arrangement determines which rule applies.

Several arguments receive separate results

Atleast_3d accepts one or more array-like inputs. With several arguments, each input receives an array result with at least three dimensions.

The function does not combine those arguments into one new shared dimension. In the reference comparison, the separate results can be inspected individually, including their different shapes.

Keep the grouping clear in written examples. Values inside one bracketed sequence belong to one input. Commas separating function arguments can instead identify several inputs, each handled on its own.

Keep the storage condition with the explanation

The documentation says that copies are avoided where possible and views with three or more dimensions are returned. Non-array inputs are converted to arrays, so a storage explanation must account for the starting input type.

A new shape is not, by itself, evidence that a separate independent copy of all numerical data has been made. Equally, copies avoided where possible should not become a promise of no allocation for every kind of input.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the starting dimensions, apply the corresponding shape rule and state where each size-one axis appears. That keeps the minimum-dimension requirement separate from the number of numerical entries and from the question of independent storage.

NumPy atleast_2d gives inputs a minimum of two dimensions without flattening higher-dimensional arrays

An input may be a single number, a one-dimensional sequence or an array that already has several dimensions. NumPy atleast_2d views inputs as arrays with at least two dimensions. The phrase at least sets a minimum. It does not mean that every result must have exactly two dimensions.

Academia Master Trader presents this explanation in English for readers in Nauru. The examples concern numerical array structure only. They are not market prices, trading signals or financial results. Reading the input and output shapes makes the function's purpose easier to understand.

A scalar becomes a one-by-one array

The NumPy reference shows np.atleast_2d(3.0) returning [[3.]] as an array. The result has one row and one column, with shape (1,1).

The single numerical value is retained. Adding dimensions does not require adding more distinct values. Here the two dimensions each have length one, so the result still contains one entry.

The decimal notation reflects the floating-point value used in this example. The important structural point is that a scalar input is represented in an array with two dimensions rather than remaining a scalar.

A one-dimensional array becomes a single row

Let x be the NumPy array containing [0.,1.,2.]. Its shape is (3,), meaning one dimension with three entries. The call np.atleast_2d(x) returns a single row containing those same values, with shape (1,3).

Original diagram: NumPy atleast_2d changes a vector of shape three into a one-row array of shape one by three, keeping the entries zero, one and two.

The result is not a column with shape (3,1). The function's one-dimensional example becomes a row. State the resulting shape explicitly when the distinction between a row and a column matters.

The entry count stays separate from dimension count

In the vector example, shape (3,) describes three entries. Shape (1,3) also describes three entries. The new size-one dimension changes the arrangement, not the number of numerical entries.

This is different from repeating the vector several times. A repeated arrangement would contain additional positions for values. The one-row result has only the original three positions.

Keep the shape beside the contents when explaining this change. The contents show which values remain, while the shape identifies how many dimensions describe them and the length of each dimension.

Existing two-dimensional arrays are preserved

The reference states that arrays that already have two or more dimensions are preserved. A two-dimensional array therefore does not need another dimension simply because it is passed to atleast_2d.

For an input whose shape is already (1,2), the minimum requirement is already met. The function is not an instruction to add one more leading dimension to every input.

This distinction separates a minimum-dimension operation from unconditional axis insertion. Before describing a shape change, identify whether the input actually falls below the two-dimensional minimum.

Higher-dimensional arrays are not flattened to a matrix

An array with three dimensions already satisfies the requirement of at least two dimensions. The documentation says that arrays with two or more dimensions are preserved, rather than reduced to exactly two.

For example, an array with shape (2,3,4) already has more than the required minimum. Atleast_2d is not a request to combine two of those dimensions into a larger row or column dimension.

Do not describe this function as a general reshape-to-matrix operation. Its name specifies a lower bound on the number of dimensions, not a target shape with exactly two positions.

Several inputs are handled individually

The function accepts one or more array-like inputs. The reference gives a call with three separate inputs: np.atleast_2d(1,[1,2],[[1,2]]).

The returned arrays represent [[1]], [[1,2]] and [[1,2]]. The scalar, the one-dimensional sequence and the already two-dimensional sequence each receive the structure appropriate to that input.

Those separate arguments are not instructions to concatenate their contents into one larger row. Read the result as a collection of results corresponding to the supplied inputs, each satisfying the minimum dimension count.

A sequence and several arguments are different requests

A call containing one sequence, such as np.atleast_2d([1,2]), supplies a single array-like input. Its two values belong to one sequence that becomes a one-row array.

A call with several separate arguments supplies several inputs for individual treatment. The distinction is in the call structure, before looking at the shapes of the returned arrays.

When recording an example, keep the brackets and commas clear. They show whether values are grouped inside one input or supplied as separate inputs. That makes the relationship between inputs and results easier to follow.

Copies are avoided where possible

The documentation says that copies are avoided where possible and that views with two or more dimensions are returned. Non-array inputs are converted to arrays, so the starting type matters when describing the operation.

In the reference's one-dimensional NumPy array example, the result's base is the original x. That illustrates a view relationship for that example. A different bracket layout does not by itself prove independent storage.

Do not turn this into a promise that every possible input requires no allocation. The documented wording is copies avoided where possible. Keep that condition when explaining the storage behaviour.

Read the minimum before predicting the shape

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the input's dimension count, then ask whether it already meets the minimum of two. For lower-dimensional inputs, state the resulting shape. For arrays already meeting the minimum, avoid describing a flattening or extra-axis step that the function does not require.

NumPy squeeze removes size-one axes while preserving the numerical entries in an array

A dimension of length one can describe a row, a column or another position in an array's shape. NumPy squeeze removes axes whose length is one. It changes the shape without selecting fewer numerical entries. The operation is about dimensions, rather than deleting values that happen to equal one.

Academia Master Trader presents this explanation in English for readers in Kiribati. The examples concern array structure only. They are not market prices, signals or financial results. A shape containing two size-one dimensions makes the operation easy to follow.

Read the input shape before removing an axis

Consider an array x containing the nested values [[[0],[1],[2]]]. Its shape is (1,3,1). The first dimension has length one, the second has length three and the third has length one.

The call np.squeeze(x) gives shape (3,). With the default axis argument, the size-one axes are removed. The length-three dimension remains, and the entries zero, one and two are retained.

Original diagram: NumPy squeeze changes shape one by three by one into shape three by removing axes zero and two, both length one, while retaining entries zero, one and two.

The result has one dimension and three entries. The value one is still present. This matters because squeeze acts on dimension lengths, not on whether an individual entry has the numerical value one.

Remove only a selected size-one axis

The optional axis argument can limit the operation. For the same input, np.squeeze(x,axis=0) produces shape (3,1). Only the first size-one axis has been removed.

The original last axis still has length one, so the result is two-dimensional. A selected axis does not mean that every other eligible size-one axis must disappear too.

The call np.squeeze(x,axis=2) instead produces shape (1,3). The last size-one axis is removed, while the leading one remains. Both calls keep the same three numerical entries but give different shapes.

The selected axis must have length one

For shape (1,3,1), the dimension at axis one has length three. The call np.squeeze(x,axis=1) raises ValueError because this dimension cannot be removed by squeeze.

The operation does not reduce the three entries to a single number. It does not choose a representative entry, calculate an average or combine neighbouring values. A selected dimension must already have length one.

Before supplying an axis, write down its length in the input shape. This gives a direct explanation of why axes zero and two are eligible in this example, while axis one is not.

Keep axis position separate from axis length

In shape (1,3,1), axis zero and axis two each have length one. The axis number names a position. The corresponding shape entry gives the length at that position.

Saying remove axis one would therefore name the middle dimension, not mean remove any dimension whose length is one. These are different uses of the number one and should be described separately.

A clear explanation states both pieces of information: remove axis zero, whose length is one. That wording avoids confusing an index with a dimension size or an array entry.

Several selected axes can be named

The reference allows axis to be an integer or a tuple of integers, as well as the default None. A tuple selects a subset of size-one dimensions for removal.

For the example shape (1,3,1), selecting axes zero and two removes the two size-one dimensions and leaves shape (3,). Each selected dimension satisfies the same length-one requirement.

Read the selected positions from the input shape. When explaining a tuple, list the dimensions it selects and the remaining dimensions in order. This makes the resulting shape easier to understand than relying only on nested brackets.

Entry count does not shrink with dimension count

The product of the input dimension lengths is one times three times one, which equals three. The output shape (3,) also describes three entries.

Removing a dimension of length one does not discard a row full of distinct data. That dimension has only one position, so removing its place in the shape does not remove the values described by the other dimensions.

This is why shape reduction and data reduction need separate names. Squeeze simplifies dimensions that have length one. It is not an operation for summarising multiple values into fewer values.

Removing every axis leaves a zero-dimensional array

The reference gives another example: an array containing [[1234]] has shape (1,1). Calling squeeze removes both size-one dimensions and produces an array with shape ().

That result is a zero-dimensional array, not an ordinary scalar. It still contains the numerical value 1234, but its shape has no dimension lengths listed.

Do not describe the empty shape tuple as an empty array. There is still one value. The absence of axes is different from the absence of entries, and the reference explicitly distinguishes this result from a scalar.

The documented result shares the input relationship

The documentation states that the result is the input itself or a view into it. A shorter shape does not establish that a separate, independent copy of the numerical data has been created.

If later work requires an independent copy, that is a separate requirement from removing size-one dimensions. Shape and storage relationship answer different questions and should be explained separately.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Read the input shape, identify dimensions of length one and state which of them are removed. Then describe the output shape without suggesting that values equal to one were deleted.

NumPy expand_dims inserts a size-one axis at a chosen position without adding new numerical entries

An array can gain a dimension without gaining more data values. NumPy expand_dims inserts a new axis at a specified position in the expanded shape. The inserted axis has length one. This changes the arrangement described by the shape, rather than repeating the existing entries.

Academia Master Trader presents this explanation in English for readers in Tuvalu. The examples concern numerical array structure only. They are not prices, trading signals or financial results. A short vector makes the difference between adding a row axis and adding a column axis easy to read.

Begin with a one-dimensional array

Let x be a NumPy array containing [1,2]. Its shape is (2,), meaning that it has one axis with two entries. The shape does not include a separate row axis and column axis.

The expression np.expand_dims(x,axis=0) gives an array with one row, [1,2], and shape (1,2). The inserted size-one dimension appears at position zero in the output shape.

Original diagram: NumPy expand_dims inserts a leading size-one axis into a vector of shape two, producing a one-row array with shape one by two and the same entries one and two.

There are still two numerical entries. The new one in the shape describes the length of the added axis. It is not an extra data value inserted before one and two.

Insert the new axis after the existing axis

For the same x, np.expand_dims(x,axis=1) produces rows [1] and [2], with shape (2,1). The original length-two dimension stays first, and the new size-one dimension appears second.

The two outputs contain the same values, but one is a single row and the other is a single column. The axis argument selects where the new dimension appears, so it changes the arrangement even when the entry count stays unchanged.

Read the output shape from beginning to end. In (1,2), the first dimension has length one. In (2,1), the second dimension has length one. Writing only that the result is two-dimensional leaves this distinction unstated.

The axis names an expanded position

The documentation defines axis as a position in the expanded axes. This is important because the position belongs to the result that includes the new axis, rather than merely naming an existing input dimension.

For the one-dimensional vector, positions zero and one can each identify a place for a new axis in a two-dimensional result. They do not select an input axis to remove or replace.

Keep the operation separate from moving an existing axis. Expand_dims adds a dimension of length one. Moving axes changes the positions of dimensions that are already present. The two operations answer different structural questions.

Shape grows while entry count stays fixed

The input shape (2,), the row shape (1,2) and the column shape (2,1) each describe two entries. Multiplying the dimension lengths gives two in each case. The extra dimension does not multiply the data into additional copies.

This is why the word expand needs a precise explanation. It is the number of dimensions that increases, not the numerical values and not necessarily the number of entries.

A small example should therefore state both the shape and the contents. The contents show that one and two are retained. The shape shows where the size-one axis has been inserted.

Several new axes can be requested

The axis argument may be a tuple. For x containing [1,2], the reference shows np.expand_dims(x,axis=(0,1)), whose result has shape (1,1,2).

Two new size-one axes appear before the original length-two dimension. The result has three dimensions but still contains only the two original numerical entries.

The reference also shows axis=(2,0), giving shape (1,2,1). The new axes occupy positions zero and two of the expanded result. The original length-two axis lies between them.

Read tuple positions in the resulting shape

A tuple names positions for the inserted axes in the expanded arrangement. It should not be described as an instruction to repeatedly insert one axis and then reinterpret every subsequent position through a separate call.

For shape (1,2,1), naming the size-one axes at positions zero and two is enough to explain the structure. The remaining position holds the input's original length-two dimension.

Write the full output shape beside a multi-axis call. Nested brackets alone can be difficult to read, especially when several dimensions have length one. A shape gives a compact account of the dimension positions.

The documented result is a view

The reference describes the result as a view of the input with the number of dimensions increased. Do not describe the different bracket layout as evidence that an independent full copy of the data was created.

If later work needs an independent snapshot, that is a separate requirement from inserting an axis. A dimension change explains the arrangement used to address entries, not a guarantee that storage has become separate.

Keep those statements distinct: the output has more dimensions, the added dimensions have length one, the original values are retained and the documented result is a view. Each statement explains a different property.

Name the new dimension and its position

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Read the input shape, identify the output positions for the new size-one axes and state the resulting shape. That keeps adding a dimension distinct from repeating values, changing their magnitude or moving an existing axis.

NumPy moveaxis places selected axes in new positions while keeping the remaining axes in their original relative order

An array's shape is an ordered description of its dimensions. NumPy moveaxis changes that order by placing selected axes at specified destinations. The axes that are not selected keep their original relative order. This makes the function useful to explain as moving dimensions within an ordered list.

Academia Master Trader presents this explanation in English for readers in Tonga. The examples concern numerical array structure only. They are not prices, trading signals or financial results. Reading the source axis and destination position separately helps distinguish movement from a simple exchange of two axes.

Start with three named dimensions

Let x be a NumPy array with shape (3,4,5). Call its axes A, B and C for the explanation, with lengths three, four and five respectively. The initial order is A, B, C.

The expression np.moveaxis(x,0,-1) gives shape (4,5,3). Axis zero, labelled A in this explanation, moves to the final position. The remaining axes B and C stay in that relative order.

Original diagram: axes A B C with lengths three four five become B C A with lengths four five three after moving source axis zero to the final destination with NumPy moveaxis.

The letters are teaching labels, not additional function arguments. They help track the dimensions through the operation. The actual call identifies the source and destination through axis positions.

A destination is a position in the output

The source argument identifies the original axis to move. The destination identifies where that axis should appear in the result. In this example, negative one names the final destination position.

The length three travels with its axis. It does not become four merely because a different axis now occupies the first position. The shape changes from (3,4,5) to (4,5,3) because the existing dimensions have been reordered.

Keep axis identifiers and dimension lengths separate. The source value zero does not mean a dimension of length zero, and the destination value negative one does not request a negative dimension length.

Move the final axis to the beginning

For the same x, np.moveaxis(x,-1,0) gives shape (5,3,4). Axis C moves from the final input position to the first output position. Axes A and B retain their relative order after it.

This result differs from moving the first axis to the end. One operation produces B, C, A; the other produces C, A, B. The same dimensions participate, but the source and destination describe different arrangements.

Read both arguments in the call. Saying that an axis moves between the beginning and the end is incomplete unless the direction of that move is also clear.

Movement is not always an exchange

For shape (3,4,5), swapping the first and final axes gives shape (5,4,3). Moving the first axis to the end instead gives (4,5,3). The middle dimension behaves differently in the two arrangements.

With moveaxis, the unselected dimensions keep their relative order. With a pairwise swap, the selected axes exchange places directly. These are different rules, even though both reorder dimensions.

Use a three-axis example when teaching this distinction. A two-axis example can make the operations look identical because there is less remaining order to observe.

Follow a single entry through its indices

An entry at input index (1,2,3) in shape (3,4,5) is identified through axes A, B and C in that order. After moving A to the final position, the same entry is identified at output index (2,3,1).

The index components move with their axes. The numerical entry stored at that location is not being multiplied or replaced. A change of coordinates within the array is separate from an arithmetic change to its contents.

This index example also shows why shape alone is not the entire explanation. The output dimensions describe the arrangement, while the index mapping connects a particular input entry to its resulting position.

Several axes can be moved together

The reference permits a sequence of source axes and a sequence of destinations. Source positions must be unique, and destination positions must also be unique. Each selected source needs a corresponding destination.

For x with shape (3,4,5), the documented example np.moveaxis(x,[0,1],[-1,-2]) gives shape (5,4,3). Axis zero moves to the final position, and axis one moves to the preceding position.

Do not explain this as a series of separate calls that continually renumber the remaining input. The source sequence identifies original axes for the requested arrangement. State the pairings clearly, then read the resulting shape.

The documented result is a view

The reference describes the returned array as a view of the input array. A new visible axis order should therefore not be described as an independent snapshot of all the numerical data.

If later work requires separate storage, that is an additional requirement. Moving axes answers an arrangement question; it does not by itself establish that later changes are isolated from the original array.

Keep the shape, index mapping and view property separate when presenting the result. They explain different aspects of the same operation and prevent a familiar-looking printed array from carrying an unsupported storage claim.

State what moves and what stays ordered

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Name each source axis, state its destination and read the remaining axes in order. That makes an axis movement clear without confusing it with a pairwise exchange, a numerical transformation or a complete reversal of every dimension.

NumPy swapaxes exchanges two array axes while leaving the other axes in their existing positions

A multidimensional array can describe the same entries through a different order of dimensions. NumPy swapaxes performs a specific version of that change: it exchanges two named axes. The function takes the input array and the two axis numbers, making the selected exchange explicit.

Academia Master Trader presents this explanation in English for readers in Samoa. The examples concern numerical arrays only. They are not prices, trading signals or financial results. Reading axis numbers separately from dimension lengths helps explain what changes and what remains in place.

Start with a matrix that has one row

Let x be a NumPy array with one row, [1,2,3], and shape (1,3). The expression np.swapaxes(x,0,1) produces three rows: [1], [2] and [3]. The output shape is (3,1).

The first axis and the second axis exchange places. The input's three-column dimension becomes the output's three-row dimension, while its single-row dimension becomes the single-column dimension.

Original diagram: NumPy swapaxes exchanges axes zero and one of a one-by-three array, turning the row one two three into three single-entry rows and changing the shape to three by one.

The values remain one, two and three. They are not summed, sorted or replaced. The operation changes how existing entries are indexed through the selected axes.

A single row is not a one-dimensional vector

The shape (1,3) contains two dimensions. The shape (3,) contains only one. Both can display the values one, two and three in a horizontal line, but they do not supply the same set of axes.

The reference's first example deliberately uses a two-dimensional input with a single row. That provides axis zero and axis one for the exchange. Do not remove the extra dimension from the explanation and still describe the same operation.

Read the shape before choosing axis numbers. An axis names a dimension that exists in the input; it is not created merely by including its number in the function call.

Axis numbers are positions, not lengths

For an input shape (2,3,4), exchanging axes zero and two gives shape (4,3,2). The middle axis remains in its original position. The lengths two and four move because the dimensions they describe have exchanged places.

The arguments zero and two identify the first and third axes. They do not request dimensions with lengths zero and two. Keep the axis identifiers separate from the numbers written in the input shape.

Writing both shapes side by side is useful. Mark the two exchanged positions and leave the middle position unmarked. That makes the scope of this operation clearer than saying that every dimension has been reversed.

A square shape can hide the exchange

The reference includes a three-dimensional array with shape (2,2,2). Exchanging axes zero and two leaves that shape unchanged, because both exchanged dimensions have length two. The entries still move to different indexed positions.

The input has two blocks: rows [0,1] and [2,3] in the first block, followed by rows [4,5] and [6,7] in the second. After np.swapaxes(x,0,2), the first block has rows [0,4] and [2,6]; the second has rows [1,5] and [3,7].

The equal dimension lengths make shape an incomplete description of the result. Read selected entries as well as the shape. An unchanged shape does not establish that the arrangement stayed unchanged.

Follow an index to understand the rule

In that three-dimensional example, the value one begins at index (0,0,1). Exchanging axes zero and two places it at (1,0,0). The middle index stays zero while the outer index positions exchange places.

This is a rule about index positions, not about reversing the values within every row. The value one remains one, and the new location follows from the selected axes.

A single traced entry can explain a large printed result. State its original index, exchange the selected index positions and identify the resulting location. That links the function call to the output without depending only on visual block layout.

Distinguish a pairwise exchange from a general permutation

Swapaxes names two axes to exchange. A general transpose can specify an entire ordering of axes. When describing a pairwise exchange, the two-axis function makes that intention direct.

For shape (2,3,4), swapping zero and one yields (3,2,4). A default transpose would instead reverse the complete axis order to (4,3,2). The two operations need not produce the same arrangement or shape.

Choose an explanation that matches the intended change. Do not call every axis operation a reversal, because a two-axis exchange can leave several other dimensions untouched.

Keep the return-value condition

The reference states that, for NumPy versions from 1.10.0 onwards, an ndarray input returns a view; otherwise a new array is created. Keep the input condition when describing storage behaviour.

A view is not automatically an independent snapshot. If later work needs separate storage, that is a different requirement from exchanging two axes. A changed printed arrangement does not itself show that a separate copy exists.

For this lesson's matrix example, name x as a NumPy array before discussing its view result. That prevents a statement about one input type from becoming a broader claim about every accepted input.

Explain the selected pair clearly

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Read the input shape, name the two axes and follow an entry into the output. This keeps a pairwise axis exchange distinct from creating a dimension, reversing entries or applying a complete default transpose.

NumPy transpose changes the order of an array's axes rather than sorting or reversing its numerical values

An array's dimensions describe how its entries are arranged. NumPy transpose changes the order of those axes. In two dimensions, it gives the familiar matrix transpose: rows become columns and columns become rows. The operation should be explained through positions and shape, rather than described as a numerical calculation.

Academia Master Trader presents this explanation in English for readers in Vanuatu. The examples concern numerical arrays only. They are not prices, trading signals or financial results. A rectangular matrix makes the change of arrangement visible, while a vector shows an important limit of the operation.

Begin with a rectangular matrix

Let a contain rows [1,2,3] and [4,5,6]. Its shape is (2,3). The expression np.transpose(a) produces rows [1,4], [2,5] and [3,6], with shape (3,2).

The first input row becomes the first output column. The second input row becomes the second output column. The value two, originally in the first row and second column, moves to the second row and first column.

Original diagram: a two-by-three matrix with rows one two three and four five six becomes a three-by-two matrix with rows one four, two five and three six after NumPy transpose.

There are six values before and after the operation. The row and column counts exchange places, but no new numerical values are created. Stating the two shapes helps separate a change of arrangement from a change of array size.

A transpose is not a quarter turn

The transposed output begins with [1,4]. A counterclockwise quarter turn of the same matrix would instead begin with [3,6]. Both can produce a three-row arrangement, but their entry positions differ.

A matching output shape therefore does not prove that two operations are equivalent. Follow a specific entry from its original row and column to its new position. That reveals the distinction more clearly than comparing only the dimensions.

Transposition is also not sorting. The output is determined by the axes, regardless of whether the numerical values happen to be increasing, decreasing or mixed. It is the positions that supply the rule.

A one-dimensional vector stays one-dimensional

For the vector [1,2,3,4], np.transpose(a) leaves the vector unchanged. Its shape remains (4,). There is only one axis, so changing the axis order does not turn it into a two-dimensional column.

The reference makes this distinction explicit. To obtain a two-dimensional column from a one-dimensional array, an additional dimension must be introduced. Transposition by itself does not supply that extra axis.

This matters when describing a vector as a row or column. A printed horizontal sequence can still be a one-dimensional array. Read its shape before assuming that transposition will exchange a row dimension with a column dimension.

The default reverses the order of axes

When axes is omitted, transpose reverses the axis order. For a two-dimensional array, (0,1) becomes (1,0). For an input shape (2,3,4,5), the default output shape is (5,4,3,2).

That rule reverses the list of dimensions, not the numerical sequence within every dimension. It should not be confused with flipping entries along an axis. An axis permutation changes which dimension occupies each position in the array description.

For a higher-dimensional input, write the original shape and its reversed order side by side. That makes the default understandable even when a full printed array would contain too many entries to read comfortably.

An explicit permutation names the input axes

The axes argument must contain a permutation of the input axes. The axis at position i in the output corresponds to input axis axes[i]. This is an output-order specification, not a list of new dimension lengths.

For an input with shape (1,2,3), np.transpose(a,(1,0,2)) gives shape (2,1,3). The output first uses input axis one, then input axis zero, then input axis two.

All input axes appear once in that specification. Do not interpret (1,0,2) as a request to create dimensions of lengths one, zero and two. The numbers identify existing axes and state their new order.

Negative axis names count from the end

The documentation allows negative indices in an axis permutation. For an input shape (3,4,5), np.transpose(a,(-1,0,-2)) gives shape (5,3,4).

Here, negative one names the final input axis and negative two names the preceding input axis. The tuple therefore chooses the third, first and second input dimensions in that output order.

The negative signs do not negate any entries and do not request negative dimension lengths. They are a convention for naming axes relative to the end of the input's axis list.

A view is returned whenever possible

The reference states that transpose returns a view whenever possible. Keep that qualification. It is more precise than saying that every possible use always creates an independent copy, or that every use has identical storage behaviour.

A displayed change in layout is not evidence of independent storage. If a later operation needs a separate snapshot of the entries, that requirement should be considered separately from the axis permutation.

When presenting an example, identify the output shape and the axis order first. Discuss storage only with the documented qualification, rather than making a broader promise from the appearance of a printed matrix.

Read positions through the shape

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. State the input shape, name the output axis order and follow one entry to its new position. Those details keep transposition distinct from rotation, reversal and adding a dimension.