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 flatten giver en endimensional kopi med en valgt rækkefølge

Når en tabel skrives som én lang række af værdier, er det ikke nok at kende antallet af elementer. Du skal også vide, hvilken rækkefølge de læses i. NumPy-arrayets flatten-metode returnerer en kopi, der er samlet i én dimension. Metodens order-argument bestemmer, hvordan elementerne følger efter hinanden i denne kopi.

Academia Master Trader præsenterer denne gennemgang på dansk for læsere i Danmark. De små arrays er undervisningseksempler, der gør det muligt at følge positioner. De er ikke markedspriser eller økonomiske resultater. Formålet er at skelne mellem den endimensionale form, værdiernes rækkefølge og den dokumenterede oplysning om, at resultatet er en kopi.

Begynd med tabellens fire værdier

Den officielle reference bruger a=np.array([[1,2],[3,4]]). Den første række indeholder et og to, mens den anden række indeholder tre og fire.

Arrayet har dermed fire værdier fordelt over to akser. En endimensional udgave indeholder stadig disse fire værdier, men formen beskriver ikke længere to rækker og to kolonner.

Det er denne ændring af struktur, som ordet flatten beskriver. Metoden lover ikke en numerisk sortering. Rækkefølgen skal læses ud fra order-argumentet og det konkrete input.

Eget diagram: tabellen med rækkerne et to og tre fire bliver et to tre fire i C-rækkefølge eller et tre to fire i F-rækkefølge; begge resultater er endimensionale kopier.

Standardvalget er C-rækkefølge

Metoden skrives som a.flatten(order='C'). Referencen viser, at a.flatten() giver [1,2,3,4] for tabellen i eksemplet.

I to dimensioner betyder C-rækkefølge, at den første række læses før den næste. Derfor kommer et og to før tre og fire i dette resultat.

Bevar sammenhængen mellem input og resultat, når du forklarer metoden. Det er ikke tilstrækkeligt at vise fire tal uden at fortælle, hvordan de oprindeligt var placeret. Den oprindelige tabel gør læsereglen synlig.

F-rækkefølge følger kolonnerne i eksemplet

Referencens næste kald er a.flatten('F'). Her er resultatet [1,3,2,4].

Den første kolonne læses før den anden. Et og tre kommer derfor før to og fire. De samme fire værdier optræder i begge resultater, men deres positioner i følgen er forskellige.

Dette er en god grund til at skrive både metodekald og resultat i dine noter. En oplysning om, at resultatet er endimensionalt, fortæller ikke alene, om værdierne blev læst rækkevis eller kolonnevis.

Kopien er en del af metodens beskrivelse

Referencen beskriver returværdien som en kopi af inputarrayet, samlet i én dimension. Det er ikke blot en tilfældig detalje ved det viste taleksempel.

Beskriv derfor ikke flatten som en garanti for en visning af det oprindelige array. Den dokumenterede regel er en kopi.

Hold også denne oplysning adskilt fra rækkefølgen. C og F vælger, hvordan værdierne læses; de ændrer ikke returtekstens beskrivelse af resultatet som en kopi. Begge eksempler skal forklares med både struktur og rækkefølge.

A afhænger af arrayets sammenhæng i hukommelsen

Order-argumentet accepterer også A. Ifølge referencen bruges kolonnevis rækkefølge, hvis arrayet er Fortran-kontiguert i hukommelsen, og ellers rækkevis rækkefølge.

Det er en betinget regel. A bør derfor ikke forkortes til et andet navn for F eller C i alle situationer.

Hvis du sammenligner resultater med A, skal inputarrayets relevante egenskab følge med forklaringen. Ellers mangler den oplysning, som afgør, hvilken af de to læseregler dokumentationen beskriver for dette valg.

K følger elementernes rækkefølge i hukommelsen

Referencen angiver K som valget, der følger den rækkefølge, elementerne forekommer i hukommelsen.

Det er en anden beskrivelse end blot at læse en tegnet tabel fra venstre mod højre. Metodens fire mulige order-værdier har hver deres dokumenterede betydning.

Undgå derfor at beskrive K som en numerisk sortering eller som et løfte om den samme følge som C for ethvert input. Den viste tabel forklarer C og F, mens parameterbeskrivelsen fastlægger betydningen af A og K.

Lignende navne betyder ikke samme returregel

Referencen henviser også til ravel og flat som relaterede muligheder. En ens talfølge på skærmen er ikke i sig selv bevis for, at forskellige operationer har samme forhold til inputdata.

Læs altid den relevante returtekst sammen med eksemplet. For flatten er kopien og den ene dimension begge udtrykkeligt angivet.

Fortsæt læringen med Academia Master Trader på academiamastertrader.com.br. Aprenda giver adgang til undervisningsmateriale. Skriv den oprindelige tabel, den valgte rækkefølge og resultatets følge sammen. Så er det tydeligt, hvilke værdier der bevares, hvordan de læses, og hvorfor den endimensionale kopi får netop denne rækkefølge.

NumPy reshape ändrar formen med en bestämd indexordning och samma antal element

En tabell med två rader och tre kolumner kan innehålla lika många värden som en tabell med tre rader och två kolumner. NumPy reshape ändrar arrayens form utan att byta ut dess data. För att förstå resultatet behöver du läsa både den nya formen och den indexordning som används när elementen hämtas och placeras i resultatet.

Academia Master Trader presenterar denna genomgång på svenska för läsare i Sverige. De små arrayerna är pedagogiska exempel för att följa positioner och dimensioner. De är inte marknadspriser eller ekonomiska resultat. Syftet är att hålla isär antal element, form och läsordning innan du beskriver vad en viss funktionsanropning gör.

Börja med en form som passar antalet element

Den officiella referensen använder a=np.array([[1,2,3],[4,5,6]]). Arrayen har sex element, ordnade i två rader med tre värden i varje rad.

Den nya formen måste vara förenlig med den ursprungliga formen. Det är inte en instruktion att fylla på med fler tal eller att ta bort värden för att få en önskad tabell.

Skriv därför antalet element bredvid formen innan du läser vidare. I detta exempel kan sex element ordnas som tre rader med två element i varje rad. Antalet värden är fortfarande sex även om längderna för de två axlarna ändras.

Eget diagram: indata med formen två gånger tre och raderna ett två tre samt fyra fem sex blir tre gånger två med raderna ett två, tre fyra och fem sex i C-ordning.

Ett heltal ger en endimensionell form

Referensen visar np.reshape(a,6), vars resultat är [1,2,3,4,5,6].

När formargumentet är ett heltal anger det längden på en endimensionell array. Här blir längden sex. Den tidigare uppdelningen i två rader och tre kolumner finns inte längre i resultatets form.

Det betyder inte att talen har sorterats. Deras följd beror på den indexordning som används för att läsa indata och skriva resultatet. Med standardordningen syns först den första radens värden och sedan den andra radens värden i detta exempel.

C och F beskriver indexordning

Standardvärdet för order är C. Då ändras det sista axelindexet snabbast, medan det första ändras långsammast.

Med F-ordning ändras det första axelindexet snabbast. Referensen visar att np.reshape(a,6,order='F') ger [1,4,2,5,3,6].

Båda resultaten innehåller samma sex värden och har samma längd. Ändå skiljer sig deras följd. Formen ensam räcker alltså inte för att beskriva hela resultatet.

Referensen betonar att C och F handlar om indexering, inte om att direkt välja den underliggande minneslayouten. Behåll den skillnaden när du förklarar anropet.

Samma ordning används vid läsning och placering

Enligt dokumentationen kan du tänka på reshape som två delar: först läses elementen till en följd med vald indexordning, sedan placeras de i den nya formen med samma sorts indexordning.

Det är särskilt viktigt när även resultatet har flera dimensioner. Att bara läsa kolumnerna i indata och sedan alltid skriva rader i resultatet beskriver inte F-ordning korrekt.

Referensens exempel med en ursprunglig form (3,2) visar att en ny form (2,3) kan ge olika tabeller för C och F. Bevara därför både indataformen och orderargumentet när du jämför två anrop. Då går skillnaden att följa steg för steg.

Minus ett låter NumPy härleda en längd

En dimension i formargumentet kan vara -1. Den längden härleds då från antalet element och de återstående dimensionerna.

För samma sex värden visar referensen np.reshape(a,(3,-1)). Resultatet har raderna [1,2], [3,4] och [5,6].

Den okända längden blir två, eftersom resultatet har tre rader och sammanlagt sex element. Minus ett betyder inte en negativ axellängd i den färdiga arrayen. Dokumentationen tillåter en sådan härledd dimension, inte flera oberoende okända längder.

En vy är möjlig men inte garanterad

Returbeskrivningen säger att resultatet blir ett nytt vyobjekt om det är möjligt, annars en kopia.

Parametern copy styr detta när den anges. Med True kopieras data. Med standardvärdet None görs en kopia bara när den behövs enligt order. Med False uppstår ett ValueError om en kopia inte kan undvikas.

Beskriv därför inte en ändrad form som ett säkert bevis på vare sig en oberoende kopia eller en vy. Dokumentationen ger inte heller någon garanti för att resultatets minneslayout är C- eller Fortran-kontinuerlig.

Fortsätt lära med Academia Master Trader på academiamastertrader.com.br. Aprenda ger tillgång till utbildningsmaterial. Skriv indataform, önskad form och indexordning tillsammans. Antalet element begränsar vilka former som passar, medan läsning och placering förklarar var värdena hamnar i den nya strukturen.

NumPy ravel creates a contiguous one dimensional result using a chosen reading order

Flattening an array answers a shape question, but it also requires an order for reading the values. NumPy ravel returns a contiguous one dimensional array containing the input elements. Its order parameter determines how those elements are read. Two results can therefore have the same length and the same values while placing those values in different sequences.

Academia Master Trader presents this guide in English for readers in Bhutan. The small arrays are educational examples for following positions. They are not market prices or financial results. The purpose is to read the shape and the order together, rather than treating every flattened display as though there were only one possible sequence.

Begin with the documented table

The official reference uses x=np.array([[1,2,3],[4,5,6]]).

The first row contains one, two and three. The second row contains four, five and six. There are six elements to read, arranged across two axes.

Ravel packs those elements into a one dimensional array. The documented output shape is (a.size,), where the length is the input's element count. The result no longer has the original pair of row and column lengths.

Original diagram: the table with rows one two three and four five six becomes one two three four five six in C order, or one four two five three six in F order.

The default follows C index order

The signature is np.ravel(a,order='C'). With the example table, np.ravel(x) gives [1,2,3,4,5,6].

In two dimensions, C order reads across the first row and then across the next. The final axis index changes fastest.

This is a rule about index order. The reference explicitly says that C and F take no account of the underlying memory layout. Avoid describing C as an instruction to preserve whatever order the array happens to have in memory.

F order reads the columns in this example

For np.ravel(x,order='F'), the documented sequence is [1,4,2,5,3,6].

The first axis index changes fastest. In this two dimensional table, the first column is read before the second, followed by the third.

The values have not been sorted numerically. Their sequence comes from the chosen reading order. The length remains six, so the output shape alone does not distinguish this result from the default result.

Higher dimensional wording needs axis precision

The row and column explanation is convenient for the two dimensional example. The reference also defines the rule in terms of axes.

In C order, the first axis index changes slowest and the final axis index changes fastest. In F order, the opposite index progression applies.

Use that axis wording when discussing inputs with more than two dimensions. A description that depends only on rows and columns can leave out which of the additional indices changes next.

A order depends on contiguity

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

For the transposed example, the documentation shows np.ravel(x.T) returning [1,4,2,5,3,6]. The call np.ravel(x.T,order='A') returns [1,2,3,4,5,6].

Keep the transposed input with both calls when comparing them. Dropping that detail would make the example look as though the order setting alone had been compared on the original table.

K order has its own definition

K order follows the order in which the elements occur in memory, with the documented qualification for negative strides.

The reference includes a reversed sequence [2,1,0]. Both its C and K ravel examples retain [2,1,0].

Do not shorten K to a promise that every reversed input returns to ascending numerical order. The documentation's reversed example shows why such a description would be wrong. Reading order and numerical sorting remain separate operations.

A copy is made only if needed

The return is contiguous and one dimensional. The reference states that a copy is made only if needed.

That is different from promising that the operation always returns a view. It is also different from saying a new independent copy is always made. Preserve the documented condition when explaining storage behaviour.

The reference contrasts related operations and notes that ravel supports K in its order argument. A similar looking flattened display does not establish identical options or storage behaviour across different functions.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Record the input, the chosen order and the resulting sequence together. The one dimensional shape states how many elements remain, while the reading rule explains their positions.

NumPy atleast 1d gives scalars an array dimension while preserving higher dimensional inputs

An instruction that requires at least one dimension is different from an instruction that flattens every input. NumPy atleast 1d converts scalar inputs to one dimensional arrays, while preserving higher dimensional inputs. That distinction makes the function useful to understand before describing a result as a vector. The minimum requirement does not erase an existing table's structure.

Academia Master Trader presents this guide in English for readers in Nepal. The small arrays are teaching examples for reading dimensionality and return structure. They are not market prices or financial results. The goal is to follow the boundary around each input and to distinguish its values from the number of axes used to arrange them.

Read the name as a minimum requirement

The signature is np.atleast_1d(*arys). The official reference describes the operation as converting inputs to arrays with at least one dimension.

Each resulting array satisfies a.ndim>=1. The greater than or equal condition matters: one dimension is the minimum, not the only permitted dimensionality.

An input that already has more dimensions can meet that requirement without being flattened. Avoid replacing the documented rule with a shorter description that says every result is one dimensional. That shorter description changes the meaning.

Original diagram: a scalar one becomes array one with shape one; an existing three by three array keeps shape three by three; separate inputs give separate array results.

A scalar becomes a one dimensional array

The first example in the reference is np.atleast_1d(1.0). Its displayed output is array([1.]).

The single value now appears inside a one dimensional array. The example does not repeat the value to create several observations. It supplies an array dimension around the scalar input.

Keep the value and the structure separate when reading this display. One numerical entry can belong to an array with one dimension. The count of entries and the count of dimensions answer different questions.

An existing table keeps its arrangement

The reference then creates x=np.arange(9.0).reshape(3,3). Its displayed arrangement has rows [0.,1.,2.], [3.,4.,5.] and [6.,7.,8.].

Passing x to np.atleast_1d(x) displays the same three by three arrangement. The input already has two dimensions, so it meets the minimum requirement.

The function does not turn those rows into a single sequence in this example. The existing two dimensional structure remains visible. This is the clearest contrast with an operation whose purpose is to flatten an array.

The identity example is specific

For that table, the reference shows np.atleast_1d(x) is x as True.

This is stronger than merely seeing equal printed numbers in the two displays: the documented expression checks whether the returned object is x itself.

Keep the condition attached to the example. The reference also accepts scalar and other array-like inputs, so one preserved table should not become a blanket claim that every possible input is returned unchanged as the same object. The return description says copies are made only if necessary.

Several inputs give separate arrays

The documented call np.atleast_1d(1,[3,4]) returns a tuple containing array([1]) and array([3,4]).

Each input has a corresponding array. The function does not concatenate the values into a single array containing one, three and four.

This boundary is easy to miss when reading nested punctuation. The outer parentheses belong to the tuple of results; the square brackets inside each array describe that array's entries. Follow one input and its output before moving to the next.

Equal dimensionality does not mean equal length

The two results in the multiple-input example both have one dimension, but they contain different numbers of values. The first has one entry and the second has two.

A minimum dimensional requirement therefore does not impose a common length on every input. Nor does it create a rectangular combined table from inputs that began separately.

Write the number of dimensions separately from the lengths of the axes when explaining such a call. This keeps a shared minimum requirement from being mistaken for a shared output shape.

Choose the description that matches the operation

The reference distinguishes conversion of scalars from preservation of higher dimensional inputs. Its return description also allows an array or a tuple of arrays, depending on the inputs supplied.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Identify each input, read its existing dimensionality and then inspect the corresponding result. Atleast 1d supplies a minimum of one dimension without requiring an existing table to lose its structure.

NumPy atleast 3d adds dimensions in documented positions rather than using one shape for every input

A minimum of three dimensions is not a complete description of an array's shape. The positions of its lengths still matter. NumPy atleast 3d supplies that minimum while using documented arrangements for one dimensional and two dimensional inputs. Reading those arrangements prevents a common shortcut: assuming that every input simply gains all its new axes at the beginning or at the end.

Academia Master Trader presents this guide in English for readers in the Maldives. The small arrays are educational examples for following shapes and return structure. They are not market prices or financial results. The goal is to keep each input's original dimensions visible while identifying the extra length one axes supplied by the function.

The function sets a lower bound

The signature is np.atleast_3d(*arys). The official reference describes its purpose as viewing inputs as arrays with at least three dimensions.

It accepts one or more array-like inputs. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

The return condition is a.ndim>=3 for each resulting array. This states a minimum, not a command to reduce every input to exactly three axes. An input already beyond that minimum does not need to be flattened to satisfy it.

Original diagram: one dimensional shape N becomes one N one; two dimensional shape M N becomes M N one; an input already having three or more dimensions is preserved.

A scalar has a three dimensional display

The reference begins with np.atleast_3d(3.0). It displays the result as array([[[3.]]]).

The nested brackets show the added dimensional structure around the value. This does not describe three copies of the numerical value. There is still one displayed entry.

When explaining the result, keep the number of dimensions separate from the number of values. Several axes of length one can surround a single value without repeating it.

A one dimensional input gains two length one axes

The return description gives the general rule: a one dimensional array of shape (N,) becomes a view of shape (1,N,1).

The original length N occupies the middle position. A new length one appears before it and another appears after it.

The reference creates x=np.arange(3.0) and shows np.atleast_3d(x).shape as (1,3,1). This concrete example makes the placement visible. The shape is not (1,1,3) and not (3,1,1) for this call.

A two dimensional input gains a final axis

The general rule for a two dimensional array of shape (M,N) is a view of shape (M,N,1).

Here the two original lengths stay in their positions, with a new length one at the end. This is a different insertion pattern from the one dimensional case, because the input starts with a different number of axes.

The documented example uses x=np.arange(12.0).reshape(4,3). The resulting shape from np.atleast_3d(x) is (4,3,1).

Reading the before and after shapes together explains the result more clearly than describing a generic conversion into a three dimensional block.

Several inputs remain separate arrays

The function can return an array or a tuple of arrays. Each result satisfies the minimum dimensional requirement independently.

The reference passes [1,2], [[1,2]] and [[[1,2]]] in one call. The printed output shapes are (1,2,1), (1,2,1) and (1,1,2) respectively.

The first two inputs reach the same shape from different starting dimensions. The third input already has three dimensions and retains its arrangement. Having the same two values does not make all three output shapes identical.

This call does not combine the inputs into one larger array. Keep each corresponding result separate when documenting it.

Views and copies are different questions

The reference says that copies are avoided where possible and that views with three or more dimensions are returned.

For its reshaped two dimensional example, it also shows np.atleast_3d(x).base is x.base as True, noting that x itself is a reshape.

Do not replace this specific relationship with a blanket statement that a printed shape change proves an independent copy. The input form and the documented return relationship both matter.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Record the input shape before reading the new one. For this function, one dimensional and two dimensional inputs use different placements for the added axes, while inputs already meeting the minimum retain their dimensions.

NumPy atleast 2d gives each input at least two dimensions without combining separate inputs

Some array operations begin with inputs that do not have the same number of dimensions. One value, a one dimensional sequence and an existing table are different starting points. NumPy atleast 2d provides a minimum dimensional requirement: each result has at least two dimensions. That wording matters. It does not mean that every input becomes exactly two dimensional, nor that separate inputs are combined into a single table.

Academia Master Trader presents this guide in English for readers in Brunei. The small arrays are educational examples for reading shape and return structure. They are not market prices or financial results. Follow the boundary around each input before reading the brackets in its result. This makes it easier to distinguish an individual array from a tuple containing several arrays.

The requirement is a minimum

The function is written as np.atleast_2d(*arys). The official reference describes its purpose as viewing inputs as arrays with at least two dimensions.

The return condition is a.ndim>=2 for each result. Read this as a lower bound on the number of dimensions, not a requested shape with a fixed number of rows or columns.

An array that already has two or more dimensions is preserved. In particular, the description does not instruct the function to reduce an input with more dimensions to a two dimensional table. The word at least prevents that misunderstanding.

Original diagram: scalar three becomes a one by one array; the sequence zero one two becomes a one by three array; two or more input dimensions are preserved.

A scalar becomes a small two dimensional array

The first example in the reference is np.atleast_2d(3.0). Its displayed output is array([[3.]]).

The double brackets show a two dimensional arrangement containing one value. The displayed value remains three; the operation supplies the dimensional structure needed for the minimum requirement.

Do not describe this as creating several new observations or repeating the input value. The documented output contains one numerical entry in an array that has at least two dimensions.

A one dimensional sequence becomes a row

The reference then creates x=np.arange(3.0). The output of np.atleast_2d(x) is displayed as array([[0.,1.,2.]]).

The three entries are together in one row. They are not displayed as three rows containing one entry each.

This orientation is worth recording alongside the function name. Saying only that a vector became two dimensional leaves out a visible part of the documented result. A row of three values and a column of three values both have two dimensions, but they have different shapes.

Existing dimensions do not need to be added again

Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved, according to the parameter description.

These are different branches of the same rule. An input does not gain another axis simply because it is passed to the function. First consider whether it already meets the minimum requirement.

The reference's multiple-input example includes [[1,2]]. That input appears in the result as array([[1,2]]), retaining its two dimensional arrangement.

Several inputs produce separate results

The documented call np.atleast_2d(1,[1,2],[[1,2]]) returns a tuple containing three arrays.

The displayed arrays are array([[1]]), array([[1,2]]) and array([[1,2]]).

Read the tuple from one result to the next. Each input has its own corresponding array. The function has not stacked all the inputs into one larger array, and the different input lengths do not become a common row length in a newly assembled table.

Keeping the outer tuple separate from the brackets inside each array is especially useful when documenting a call with several inputs.

Copies are avoided where possible

The return description says that copies are avoided where possible and that views with two or more dimensions are returned.

For the one dimensional array example, the reference shows np.atleast_2d(x).base is x as True.

Keep this documented example distinct from a claim that every possible input follows exactly the same storage path. The parameter description also allows non-array inputs, which are converted to arrays. A new printed arrangement should not automatically be described as an independent copy.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Identify each input, read its dimensionality and then inspect its corresponding result. The function sets a minimum of two dimensions while preserving the distinction between separate inputs and their separate arrays.

NumPy squeeze removes length one axes without turning every result into a scalar

An array can contain an axis of length one without containing only one value overall. NumPy squeeze removes axes whose lengths are one. It can remove all such axes or only a selected subset. Reading the shape first is the clearest way to understand which positions can be removed and what the remaining shape will describe.

Academia Master Trader presents this guide in English for readers in Sri Lanka. The arrays are small teaching examples for following dimensions. They are not market prices or financial results. The aim is to separate three ideas: the number of values, the number of dimensions and the length of each axis. Those quantities play different roles in the operation.

Start with the documented shape

The official reference creates x=np.array([[[0],[1],[2]]]). Its shape is (1,3,1).

There are three axes. Axis zero has length one, axis one has length three, and axis two has length one.

The input contains three values, even though two entries of its shape are one. A length one axis describes a part of the array structure. It does not say that the entire array has just one element.

Original diagram: input shape one three one; the default squeeze gives shape three, axis zero gives shape three one, and axis two gives shape one three.

The default removes both length one axes

For this input, np.squeeze(x).shape is (3,) in the reference.

Axis zero and axis two both qualify for removal, so the remaining result has one dimension with length three. The values zero, one and two remain represented by that length three axis.

The default axis parameter is None. In this case, it removes all length one axes rather than choosing just the first one. Stating this rule matters because several such axes can occur in one shape.

Selecting axis zero keeps the final axis

The call np.squeeze(x,axis=0).shape gives (3,1).

Only the selected leading axis is removed. The trailing length one axis remains because this call chose a subset of the eligible axes.

The result therefore still has two dimensions. A reader looking only at the values might overlook this difference, so write the output shape beside the call. Removing one eligible axis and removing every eligible axis are distinct instructions.

Selecting axis two keeps the first axis

The call np.squeeze(x,axis=2).shape gives (1,3).

Now the trailing length one axis is removed and the leading length one axis remains. Compare this with (3,1) from the previous call.

Both outputs describe three values and both have two dimensions. Their shape entries have different positions, however. They cannot be treated as interchangeable shapes merely because their element counts agree.

Axis one cannot be removed in this input

The reference shows that np.squeeze(x,axis=1) raises a ValueError. Axis one has length three, not length one.

This is a condition on the selected axis, rather than a request to reduce that axis to length one. Squeeze does not choose a value from the length three axis to make the instruction fit.

Before specifying an axis, locate its entry in the input shape. The axis number and the axis length are not the same quantity. Here, axis one happens to have length three; the number one in its name does not make it eligible for removal.

A tuple can select a subset

The axis parameter accepts an integer or a tuple of integers, as well as the default None.

The reference describes this selection as a subset of entries of length one in the shape. Every selected axis must satisfy that length condition.

Keep the exact selection with the input shape when explaining a call. A tuple of axis positions is not a tuple of new lengths. It tells the operation which eligible positions to remove, rather than describing a replacement shape directly.

Removing every axis still returns an array

The documentation also uses x=np.array([[1234]]), whose shape is (1,1).

After np.squeeze(x), the displayed result is array(1234) and its shape is (). The reference explicitly identifies this as a zero dimensional array, not a scalar.

It also shows np.squeeze(x)[()] yielding 1234. Keep that extra indexing step distinct from the squeeze operation itself. A single displayed value does not by itself establish that the result of a function is a scalar.

The return relationship matters too

The documented result is always the input itself or a view into it. Do not describe a smaller shape as a promise of a new independent copy.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Read the full input shape, identify the length one entries and keep the selected axes visible in your notes. Squeeze removes eligible axes, while the remaining lengths explain the output structure.

NumPy expand_dims inserts a new axis at a chosen position in the expanded shape

A sequence of two values and a table with one row of two values contain the same number of elements, but they have different shapes. NumPy expand_dims makes this distinction explicit. It inserts a new axis at a selected position in the expanded shape. The result has more dimensions, and the position of the inserted axis determines how the existing values are arranged within that shape.

Academia Master Trader presents this guide in English for readers in Malaysia. The small arrays are educational examples for reading dimensions and brackets. They do not represent market prices or financial results. Following the shapes alongside the values makes the operation easier to describe than relying on the visual direction of a printed array alone.

Begin with a one dimensional array

The official reference uses x=np.array([1,2]). Its shape is (2,).

That shape has one entry, so the array has one dimension. The entry says that the existing axis has length two. The comma in the tuple notation is meaningful; it helps show that this is a shape tuple containing one length.

Neither of the next examples changes the two displayed values into a different sequence. Their difference is where the additional axis appears.

Original diagram: the input shape two becomes shape one by two with axis zero, or shape two by one with axis one; both outputs contain the values one and two.

Axis zero inserts a length one axis first

The call np.expand_dims(x,axis=0) produces an array displayed as [[1,2]]. Its shape is (1,2) in the documentation.

Read the shape from the beginning. The inserted axis has length one, followed by the existing length two. In a two dimensional display, that gives one row containing two entries.

The number of dimensions has increased from one to two. The number of values remains two. These are different quantities, so an explanation should not use the word size when it really means the number of axes.

Axis one inserts the new axis after the existing one

The call np.expand_dims(x,axis=1) produces the two dimensional arrangement [[1],[2]]. The reference gives its shape as (2,1).

Now the existing length two comes first, followed by the inserted length one. The display has two rows, with one entry in each row.

Both (1,2) and (2,1) describe arrays with two values. They are not interchangeable descriptions of the same shape. The choice of axis is the reason the arrangements differ.

Read axis as a position in the expanded shape

The reference defines axis as the position in the expanded axes where the new axis is placed. This is more precise than describing it as a selection of an existing row or column.

For the one dimensional input, axis zero creates the leading position and axis one creates the following position. Those choices produce a result with two axes.

Write the input shape, then write the intended output shape before explaining the call. This simple comparison keeps the new length one separate from the original length two, especially when several surrounding brackets are visible.

A tuple can insert several axes

The axis parameter can be an integer or a tuple of integers. The documentation includes np.expand_dims(x,axis=(0,1)), whose displayed result is [[[1,2]]].

It also includes np.expand_dims(x,axis=(2,0)), with displayed result [[[1],[2]]].

The tuple describes positions for new axes. It is not a tuple of data values to append to the array, nor a list of replacement lengths for the original axis.

With several inserted axes, follow the nesting of brackets carefully. Keep the exact axis tuple beside the example rather than describing every three dimensional result as though it had the same arrangement.

The result is a view

The reference describes the returned array as a view of the input, with the number of dimensions increased.

That return description is part of the function's behaviour. Do not describe the operation as a promise of an independent copy merely because the printed output has a new shape.

A shape change and a copy are separate ideas. Naming the result as a view gives the reader the documented relationship without inventing an extra data duplication step.

For axis zero, the reference gives equivalent indexing forms using x[np.newaxis,:] or x[np.newaxis]. For axis one, it gives x[:,np.newaxis].

These forms connect the new axis position with familiar indexing notation. The reference also notes that np.newaxis and None are the same object.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Keep the input shape, inserted positions and output shape together in your notes. Expand dims adds axes; the examples show why the location of a new length one matters even when the original values stay easy to recognise.

NumPy roll shifts array elements with wraparound while keeping the original shape

Moving values through an array does not always mean removing the values that reach an edge. NumPy roll shifts elements and brings values that pass the last position back to the first. The output has the same shape as the input. To explain a result clearly, read both the shift and the axis choice. Leaving out the axis has a specific meaning, rather than selecting the first axis automatically.

Academia Master Trader presents this guide in English for readers in Pakistan. The numbers are teaching examples for following positions in arrays. They are not market prices or financial results. The aim is to distinguish a circular shift of elements from a change in the order of the axes, then compare an explicit axis with the default behaviour.

A shift moves values by a number of places

The signature is np.roll(a,shift,axis=None). The first argument is the input array. The shift gives the number of places by which elements move.

The official reference starts with the sequence from zero to nine. A shift of two produces [8,9,0,1,2,3,4,5,6,7].

Eight and nine do not disappear when they move beyond the end. They return at the beginning. This wraparound is the detail that separates the operation from a description that simply says the values move right.

Original diagram: rolling the sequence zero through nine by two places gives eight nine zero one two three four five six seven; the final two elements wrap to the beginning.

A negative shift changes the direction

For the same input, np.roll(x,-2) produces [2,3,4,5,6,7,8,9,0,1] in the documentation.

The first two values now appear at the end. The sign of the shift is therefore part of the instruction and must remain in any explanation of the call.

Neither result is a numerical sort. The values follow the movement of their positions, with wraparound at the boundary. Their original sequence remains recognisable as a circular arrangement.

A two dimensional input makes the axis choice visible

The reference reshapes the sequence into a table with shape (2,5). Its first row is [0,1,2,3,4] and its second row is [5,6,7,8,9].

This array has axis zero and axis one. Their lengths are two and five respectively.

The axis number is not the shift amount. One identifies the direction within the array structure; the other states how many places the values move. Keeping these roles separate helps explain why two calls with the same shift can produce different arrangements.

Without an axis, flattening comes first

By default, NumPy flattens the input before shifting and restores the original shape afterwards.

For np.roll(x2,1), the reference shows rows [9,0,1,2,3] and [4,5,6,7,8].

The four has crossed the displayed row boundary because the shift was applied to the flattened arrangement. The original shape is restored, but the operation was not a separate shift within each row. This is why omitting the axis cannot be described as choosing axis zero or axis one.

Axis zero shifts the rows in this example

For np.roll(x2,1,axis=0), the output begins with [5,6,7,8,9], followed by [0,1,2,3,4].

The two rows have changed places. Each row keeps its internal sequence of values.

The documentation also shows the same displayed result for a shift of negative one along axis zero in this particular two-row array. Do not turn that local coincidence into a general rule that positive and negative shifts always agree. Read it with the length of this axis in mind.

Axis one shifts within each row

For np.roll(x2,1,axis=1), the rows become [4,0,1,2,3] and [9,5,6,7,8].

Each row wraps independently along axis one. The final value of the first row returns to the start of that row, rather than moving into the other row.

Compare this with the flattened default result. Both calls preserve shape (2,5), but the values occupy different positions. Shape alone does not tell you which axis behaviour was used.

Several axes can have corresponding shifts

The shift and axis parameters can both be tuples. The reference pairs shifts (2,1) with axes (1,0).

This assigns a shift of two to axis one and a shift of one to axis zero. The documented rows are [8,9,5,6,7] and [3,4,0,1,2].

Preserve the pairing order when describing such an instruction. A tuple of shifts is not a list of desired output lengths, and roll does not move the axes themselves to new positions.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational resources. Read the signed shift, identify whether an axis is supplied, and follow a few values across the boundary. The output keeps the original shape, while the chosen shifting rule determines where the elements appear.

NumPy rot90 fait tourner un tableau par quarts de tour dans un plan choisi

Faire tourner un tableau n'est pas la même opération qu'inverser simplement l'ordre de ses lignes. NumPy rot90 applique des rotations de quatre-vingt-dix degrés dans un plan défini par deux axes. Pour lire le résultat, il faut connaître le nombre de quarts de tour et l'ordre de ces axes. Dans le cas classique d'une matrice avec les paramètres par défaut, la rotation se fait dans le sens contraire des aiguilles d'une montre.

Academia Master Trader propose cette explication en français aux lecteurs du Liban. Les nombres servent de repères dans un tableau pédagogique. Ils ne correspondent ni à des cours ni à des résultats financiers. Le but est de suivre quelques valeurs pendant une rotation, puis de distinguer les paramètres qui déterminent son nombre de répétitions et le plan concerné.

La signature expose trois repères

La signature est np.rot90(m,k=1,axes=(0,1)). Le paramètre m désigne le tableau d'entrée.

Le paramètre k indique combien de fois la rotation de quatre-vingt-dix degrés est appliquée. Sa valeur par défaut est un.

Le paramètre axes indique les deux axes qui définissent le plan de rotation. Ils doivent être différents. L'entrée doit posséder au moins deux dimensions : un plan ne se décrit pas avec le seul axe d'un vecteur à une dimension.

Une matrice de quatre valeurs suffit pour commencer

La référence officielle utilise une matrice m affichée [[1,2],[3,4]]. La première ligne contient un et deux ; la seconde contient trois et quatre.

Les quatre valeurs occupent des positions faciles à suivre dans un carré. Le un se trouve en haut à gauche, le deux en haut à droite, le trois en bas à gauche et le quatre en bas à droite.

Ces repères décrivent l'affichage de cet exemple. Ils servent à relire la sortie, sans remplacer la définition générale par les axes.

Schéma original : rot90 transforme la matrice un deux puis trois quatre en deux quatre puis un trois avec un quart de tour contraire aux aiguilles d'une montre et les axes par défaut.

Un quart de tour avec les paramètres par défaut

L'appel np.rot90(m) produit les lignes [2,4] et [1,3] dans la documentation.

La colonne de droite de l'entrée devient la première ligne de la sortie. Le deux passe en haut à gauche et le quatre en haut à droite.

Le un passe en bas à gauche, tandis que le trois se retrouve en bas à droite. Suivre ces quatre positions permet de reconnaître le quart de tour contraire aux aiguilles d'une montre pour cette matrice et ces paramètres.

Deux quarts de tour donnent une autre sortie

La référence donne aussi np.rot90(m,2). Le résultat affiché est [[4,3],[2,1]].

Le paramètre k vaut alors deux. Il demande deux rotations successives de quatre-vingt-dix degrés, soit un demi-tour.

Ce nombre n'est pas un numéro d'axe. Le lire comme une direction dans le tableau conduirait à confondre deux paramètres distincts. Pour commenter l'appel, annoncez d'abord le nombre de quarts de tour, puis les axes qui définissent le plan de rotation.

L'ordre des axes détermine le sens

La documentation précise que la direction va du premier axe vers le second. L'ordre du couple d'axes a donc une signification.

Elle indique que np.rot90(m,k=1,axes=(1,0)) est l'opération inverse de np.rot90(m,k=1,axes=(0,1)).

Elle donne également l'équivalence entre le premier appel et np.rot90(m,k=-1,axes=(0,1)). Cette relation montre pourquoi il faut conserver le signe de k et l'ordre des axes quand on décrit une rotation.

Un tableau peut posséder davantage de dimensions

La référence présente un tableau de forme (2,2,2) contenant les nombres de zéro à sept. Son premier bloc comprend les lignes [0,1] et [2,3], son second [4,5] et [6,7].

L'appel np.rot90(m,1,(1,2)) agit dans le plan des axes un et deux.

Le résultat contient les blocs [[1,3],[0,2]] et [[5,7],[4,6]]. Les valeurs de cet exemple rendent visible le plan choisi. Il serait insuffisant de parler d'une rotation sans préciser ces deux axes.

Le résultat est une vue tournée de l'entrée

La documentation décrit la sortie comme une vue tournée du tableau initial. Il ne faut donc pas annoncer une copie indépendante garantie.

Cette propriété se distingue du nombre de rotations et du plan sélectionné. Un commentaire clair garde ces aspects séparés.

Rot90 ne classe pas les nombres selon leur valeur. L'ordre affiché provient de leur nouvelle position après les quarts de tour demandés, et non d'un tri numérique.

Poursuivez votre apprentissage avec Academia Master Trader sur academiamastertrader.com.br. Aprenda donne accès aux ressources pédagogiques. Repérez le nombre de dimensions, lisez k et conservez l'ordre des deux axes. Suivez ensuite quelques valeurs jusqu'à leurs nouvelles positions pour expliquer précisément la rotation obtenue.