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 swapaxes vaihtaa kahden akselin paikat, ei taulukon ulottuvuuksien määrää

Moniulotteisen taulukon muoto kertoo, kuinka monta paikkaa kullakin akselilla on. Jos kaksi akselia vaihtaa paikkaa, myös niiden tehtävät vaihtuvat. NumPyn swapaxes tekee juuri tämän: se vaihtaa kaksi nimettyä akselia keskenään. Toimintoa ei pidä sekoittaa lukuarvojen järjestämiseen suuruuden mukaan eikä uuden ulottuvuuden lisäämiseen.

Academia Master Trader esittelee tämän oppaan suomeksi Suomessa oleville lukijoille. Pienet taulukot ovat opetusesimerkkejä, joiden avulla paikkoja voi seurata käsin. Ne eivät kuvaa markkinahintoja tai taloudellisia tuloksia. Tavoitteena on ymmärtää syötteen muoto, valittujen akselien numerot ja tuloksen rakenne yhdessä, ei opetella irrallista komentoa ilman selitystä.

Kaksi akselia annetaan erikseen

Virallisen viitteen kutsumuoto on np.swapaxes(a,axis1,axis2). Ensimmäinen argumentti sisältää syötteen. Seuraavat kaksi argumenttia ilmoittavat keskenään vaihdettavat akselit.

Dokumentaatio kuvaa syötteen array-tyyppiseksi muunnettavana arvona ja akselien numerot kokonaislukuina. Tuloksena saadaan ndarray.

Pidä akselin numero erillään akselin pituudesta. Akseli nolla tarkoittaa ensimmäistä akselia, ei tyhjää taulukkoa eikä nollan pituista ulottuvuutta. Akselin sisältämien paikkojen määrä näkyy taulukon muodossa. Tämä ero auttaa lukemaan esimerkkejä oikein.

Yksi rivi muuttuu yhdeksi sarakkeeksi

Viitteen ensimmäinen esimerkki alkaa taulukosta x=np.array([[1,2,3]]). Siinä on yksi rivi ja kolme saraketta. Muoto on siis (1,3).

Kutsu np.swapaxes(x,0,1) antaa kolme riviä, joissa jokaisessa on yksi arvo: ensin yksi, sitten kaksi ja lopuksi kolme.

Tuloksen muoto on (3,1). Ensimmäisen ja toisen akselin pituudet ovat vaihtaneet paikkaa. Molemmissa taulukoissa on silti kaksi akselia ja kolme arvoa. Toiminto muuttaa rakennetta akselien vaihdon mukaisesti, ei arvojen kokonaismäärää.

Oma kaavio: rivitaulukko yksi kaksi kolme, muoto yksi kertaa kolme, muuttuu saraketaulukoksi, muoto kolme kertaa yksi; akselit nolla ja yksi vaihtavat paikkaa.

Sisäkkäiset sulkeet kertovat rakenteesta

Riviesimerkin ulommat hakasulkeet ja sisemmät hakasulkeet ovat tärkeitä. Ne näyttävät, että syöte on kaksiulotteinen.

Yksittäinen lukujono ilman samaa sisäkkäistä rakennetta olisi eri lähtökohta. Älä siis poista sulkeita selityksestä vain siksi, että arvot näyttävät samoilta.

Kun kirjoitat muistiinpanoja, aseta syöte, kutsu ja tulos lähekkäin. Näin lukija voi yhdistää akselin nolla ja akselin yksi juuri siihen taulukkoon, jota komento käsittelee. Pelkkä tulos ei kerro, miten akselit oli alun perin järjestetty.

Kolmiulotteinen esimerkki paljastaa enemmän

Dokumentaatio näyttää myös syötteen x=np.array([[[0,1],[2,3]],[[4,5],[6,7]]]). Tässä muodoksi tulee (2,2,2).

Kutsu np.swapaxes(x,0,2) vaihtaa ensimmäisen ja viimeisen akselin. Viitteen tuloksessa ensimmäinen osa sisältää rivit [0,4] ja [2,6]. Toinen osa sisältää rivit [1,5] ja [3,7].

Tässä esimerkissä kaikki akselit ovat yhtä pitkiä. Siksi muoto pysyy samana, vaikka arvojen paikat vaihtuvat. Samana pysyvä muoto ei siis yksin osoita, että taulukon rakenne olisi pysynyt merkitykseltään ennallaan.

Seuraa yhtä arvoa kerrallaan

Kolmiulotteista tulosta on helpompi lukea, kun seuraat ensin vain yhtä pientä osaa. Alkuperäisen ensimmäisen rivin nolla ja yksi eivät jää samaan ensimmäiseen tulosriviin.

Tuloksen ensimmäinen rivi sisältää nollan ja nelosen. Tämä vastaa dokumentaation näyttämää akselien nolla ja kaksi vaihtoa.

Älä päättele sääntöä pelkästään siitä, mitkä luvut ovat vierekkäin yhdessä tulosteessa. Sääntö perustuu akseleihin. Esimerkin arvot auttavat näkemään seurauksen, mutta eivät korvaa akselien numerointia tai alkuperäisen rakenteen kuvausta.

Palautusarvon suhde syötteeseen on dokumentoitu

Viite rajaa palautusarvon kuvauksen NumPyn versioille 1.10.0 ja uudemmille. Kun syöte on ndarray, palautetaan näkymä siihen. Muussa tapauksessa luodaan uusi taulukko.

Tätä ei pidä tiivistää väitteeksi, että swapaxes tekisi aina itsenäisen kopion. Myös syötteen tyyppi kuuluu selitykseen.

Dokumentaatio mainitsee vanhemmille versioille erillisen säännön. Jos käsittelet vanhaa ympäristöä, älä siirrä nykyisen viitteen versiokohtaista lausetta siihen tarkistamatta soveltuvuutta. Tavallisessa nykyisen viitteen esimerkissä x on nimenomaan ndarray.

Muoto ja sisältö täydentävät toisiaan

Ensimmäinen esimerkki näyttää muodon muutoksen (1,3) muodoksi (3,1). Toinen näyttää, miksi samanpituiset akselit voivat peittää vaihdon, jos katsot vain muotoa.

Molemmissa tapauksissa hyödyllinen selitys sisältää samat tiedot: alkuperäinen rakenne, vaihdettavat akselit sekä tuloksen rakenne ja arvot.

Jatka oppimista Academia Master Traderin kanssa osoitteessa academiamastertrader.com.br. Aprenda tarjoaa opetusmateriaalia. Kirjoita akselien numerot näkyviin ennen tuloksen tulkintaa. Näin erotat kahden akselin paikanvaihdon uuden akselin lisäämisestä ja ymmärrät, miksi sama lukumäärä tai sama muoto ei yksin kuvaa koko muutosta.

NumPy transpose bytter aksenes rekkefølge, ikke antallet dimensjoner

En tabell med rader og kolonner kan vises med kolonnene som nye rader. I NumPy er dette ett eksempel på en mer generell operasjon: transpose endrer rekkefølgen på aksene. Funksjonen returnerer et array med omordnede akser. Den gjør ikke automatisk en endimensjonal følge om til en todimensjonal kolonne.

Academia Master Trader presenterer denne gjennomgangen på norsk bokmål for lesere i Norge. De små arrayene er undervisningseksempler som gjør aksene lette å følge. De beskriver ikke markedspriser eller økonomiske resultater. Målet er å lese form, aksevalg og returverdi sammen, slik at et resultat kan forklares ut fra dokumentasjonen.

Start med en tabell i to dimensjoner

Den offisielle referansen viser a=np.array([[1,2],[3,4]]). Første rad inneholder en og to, mens andre rad inneholder tre og fire.

Kallet np.transpose(a) gir radene [1,3] og [2,4]. Den første opprinnelige kolonnen blir altså den første nye raden. Den andre kolonnen blir den andre nye raden.

Arrayet er fortsatt todimensjonalt. Det er aksenes roller som byttes. I dette kvadratiske eksemplet er formen den samme før og etter, selv om plasseringen av verdiene endres. Formen alene forteller derfor ikke hele historien.

Eget diagram: radene en to og tre fire blir en tre og to fire etter transpose; begge tabellene har formen to ganger to.

Standardvalget snur rekkefølgen på alle aksene

Funksjonen skrives som np.transpose(a,axes=None). Når axes ikke er oppgitt, snus rekkefølgen på inputarrayets akser.

Referansen uttrykker dette som np.transpose(a).shape==a.shape[::-1]. For en todimensjonal tabell betyr det at de to aksene bytter plass.

Den samme regelen gjelder flere dimensjoner. Dokumentasjonen viser et array med formen (2,3,4,5). Etter transpose uten et eget aksevalg er formen (5,4,3,2).

Dette eksemplet handler om fire akser, ikke om å sortere de enkelte tallverdiene. Hold størrelsen på hver akse adskilt fra innholdet i arrayet.

Et eksplisitt aksevalg beskriver nye posisjoner

Argumentet axes kan være en tuple eller liste med en permutasjon av aksenumrene. Hver opprinnelig akse må inngå i denne omordningen.

Regelen i referansen er presis: akse nummer i i resultatet tilsvarer inputaksen som står på plass i i axes. Les derfor listen som en oppskrift for resultatets akser.

Dokumentasjonen bruker et array med formen (1,2,3). Kallet np.transpose(a,(1,0,2)) gir formen (2,1,3).

Den første nye aksen kommer fra opprinnelig akse en. Den neste kommer fra opprinnelig akse null. Den siste beholder opprinnelig akse to. Størrelsene flyttes i denne rekkefølgen, mens antallet akser fortsatt er tre.

Negative aksenumre kan også brukes

Referansen tillater negative indekser i axes. Et eksempel begynner med formen (3,4,5) og bruker (-1,0,-2).

Resultatets form blir (5,3,4). Den siste inputaksen står først i den nye rekkefølgen. Deretter følger inputakse null og den nest siste inputaksen.

Skriv gjerne både opprinnelig form og ny form ved siden av aksevalget. Da blir det lettere å se hvilken størrelse som følger hvilken akse. Bare å skrive resultatet uten aksevalget skjuler forklaringen på omordningen.

En endimensjonal følge blir ikke en kolonne av seg selv

Dokumentasjonen viser også a=np.array([1,2,3,4]). Kallet np.transpose(a) gir den samme endimensjonale følgen.

En enkelt akse har ingen annen akse å bytte plass med. Referansen beskriver derfor resultatet for et endimensjonalt array som en uendret visning av originalen.

For å få en todimensjonal kolonne må en ekstra dimensjon legges til. Referansen nevner blant annet a[:,np.newaxis] og np.atleast_2d(a).T.

Dette skiller to spørsmål som ofte blandes sammen: å endre aksenes rekkefølge og å innføre en ny akse. Transpose er ikke alene en generell løsning på begge.

En visning returneres når det er mulig

Returteksten sier at resultatet har inputarrayets akser permutert, og at en visning returneres når det er mulig.

Ikke erstatt dette med et løfte om at funksjonen alltid lager en uavhengig kopi. Den dokumenterte formuleringen er mer avgrenset.

Når du sammenligner transpose med andre operasjoner, bør returregelen følge med forklaringen. Like verdier eller samme form på skjermen er ikke nok til å fastslå forholdet mellom resultatet og de opprinnelige dataene.

Fortsett læringen med Academia Master Trader på academiamastertrader.com.br. Aprenda gir tilgang til undervisningsmateriale. Noter inputformen, aksevalget og resultatets form sammen. Da kan du forklare hvilke akser som bytter plass, hvilke størrelser som følger dem, og hvorfor antallet dimensjoner ikke øker bare fordi et array transponeres.

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.