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 trace addiert eine gewählte Diagonale statt alle Matrixeinträge zusammenzufassen

Eine Matrix lässt sich auf verschiedene Arten zusammenfassen. Man kann alle Einträge addieren, jede Zeile einzeln betrachten oder einer Diagonale folgen. NumPy trace bildet die Summe entlang einer gewählten Diagonale. Welche Einträge zur Summe gehören, hängt vom Versatz und von den beiden ausgewählten Achsen ab.

Academia Master Trader bietet diese deutschsprachige Erklärung für Leserinnen und Leser in Österreich an. Die Zahlen sind frei gewählt und dienen dazu, Positionen, Achsen und Summen zu erklären. Sie sind keine Marktpreise, Handelssignale oder finanziellen Ergebnisse. Im Mittelpunkt steht die Frage, welche Einträge in eine bestimmte Summe eingehen.

Die Hauptdiagonale einer Matrix verfolgen

Betrachten wir die Matrix a mit den Zeilen [2,5,8], [11,14,17] und [20,23,26]. Der Aufruf np.trace(a) ergibt 42. Die ausgewählten Einträge sind 2,14 und 26. Ihre Positionen lauten (0,0), (1,1) und (2,2). Zeilenindex und Spaltenindex steigen gemeinsam an.

Die Rechnung lautet 2+14+26=42. Die übrigen sechs Einträge gehen nicht in diese Summe ein. Der Aufruf liefert für diese zweidimensionale Matrix einen einzelnen Summenwert. Er gibt nicht die Folge [2,14,26] zurück und erzeugt auch keine neue Matrix mit diesen Einträgen.

Eigenes Schaubild mit der Hauptdiagonale einer Matrix und der Summe 2 plus 14 plus 26 gleich 42

Auswahl und Summe auseinanderhalten

Die verwandte Funktion diagonal wählt Diagonaleinträge aus. Trace geht einen Schritt weiter und addiert die ausgewählten Werte. Für das Beispiel liefert np.diagonal(a) die Folge [2,14,26], während np.trace(a) den Wert 42 liefert. Beide Ergebnisse beantworten unterschiedliche Fragen.

Die Folge erhält die einzelnen Beiträge. Die Summe fasst diese Beiträge zusammen. Wer später jeden Beitrag getrennt benötigt, kann ihn aus dem einzelnen Summenwert nicht eindeutig wiederherstellen. Deshalb sollte eine Erklärung klar benennen, ob eine Auswahl oder eine Zusammenfassung der Diagonale gemeint ist.

Mit einem positiven Versatz oberhalb auswählen

Das Argument offset verschiebt die gewählte Diagonale gegenüber der Hauptdiagonale. Mit np.trace(a,offset=1) werden 5 und 17 addiert. Die Summe beträgt 22. Diese Einträge liegen an den Positionen (0,1) und (1,2), also oberhalb der Hauptdiagonale bei der üblichen Zeilen- und Spaltenanordnung.

Mit offset=2 bleibt nur der Eintrag 8 an der Position (0,2). Die Summe beträgt daher 8. Der Versatz wird nicht zu den Zahlen addiert. Er bestimmt den ausgewählten Weg durch die Matrix. Ein anderer Weg kann weniger Einträge enthalten und damit auch eine andere Anzahl von Beiträgen liefern.

Mit einem negativen Versatz unterhalb auswählen

Der Aufruf np.trace(a,offset=-1) addiert 11 und 23. Das Ergebnis ist 34. Die ausgewählten Positionen sind (1,0) und (2,1). Bei offset=-2 wird nur der Eintrag 20 erfasst. Das Minuszeichen gehört zum Versatz und verändert nicht das Vorzeichen der gespeicherten Werte.

Diese Unterscheidung lässt sich durch eine kleine Positionsliste sichtbar machen. Zuerst werden die Koordinaten notiert, danach die dort stehenden Werte und zuletzt ihre Summe. So bleibt die Auswahlregel von der anschließenden Addition getrennt. Die Rechnung lässt sich dann Schritt für Schritt nachvollziehen.

Eine rechteckige Matrix genügt

Trace benötigt keine quadratische Matrix. Nehmen wir b mit den Zeilen [2,5,8] und [11,14,17]. Die Form ist (2,3). Die Hauptdiagonale enthält 2 und 14, daher ergibt np.trace(b) den Wert 16. Nach der zweiten Zeile kann dieser Weg nicht weitergehen.

Für dieselbe Matrix ergibt offset=1 die Summe 5+17=22. Bei offset=-1 bleibt nur 11. Die vorhandenen Positionen beider Achsen begrenzen die Diagonale. Es wird keine zusätzliche Zeile erzeugt, um die Anzahl der Zeilen an die Anzahl der Spalten anzupassen.

Bei mehreren Dimensionen die Achsen nennen

Die Argumente axis1 und axis2 bestimmen die beiden Achsen der betrachteten Ebenen. Ihre Standardwerte sind 0 und 1. Bei einem Array mit mehr als zwei Dimensionen müssen diese Achsen zu der Struktur passen, deren Diagonalen zusammengefasst werden sollen. Die Funktion kennt Achsennummern, aber nicht deren fachliche Bedeutung.

Die Dokumentation beschreibt die Ausgabeform als Eingabeform ohne die beiden ausgewählten Achsen. Bei einer Eingabe mit der Form (4,3,3) und axis1=1 sowie axis2=2 hat die Ausgabe die Form (4,). Jede der vier drei mal drei großen Ebenen liefert einen eigenen Summenwert. Das Ergebnis ist dann nicht eine einzige Summe über das ganze Array.

Den Zahlentyp bewusst wählen

Das Argument dtype bestimmt den Typ der Ausgabe und des Akkumulators, in dem addiert wird. Die Dokumentation erläutert außerdem, wann kleine ganzzahlige Eingabetypen ohne ausdrückliche Angabe auf die übliche Ganzzahlgenauigkeit angehoben werden. Der Datentyp gehört daher zur Beschreibung einer numerischen Rechnung.

Die mathematisch erwartete Summe und ihre Darstellung im gewählten Datentyp sind getrennte Fragen. Prüfen Sie, ob der Typ für die vorgesehenen Werte geeignet ist. Ein zusätzlicher Parameter out kann einen passenden Ausgabebereich vorgeben; dessen Form muss das Ergebnis aufnehmen können, und sein Typ bleibt erhalten.

Die Bedeutung der Summe nicht voraussetzen

Trace beschreibt eine bestimmte Auswahl und Addition. Ob die Hauptdiagonale in einem Datensatz eine sinnvolle fachliche Beziehung darstellt, hängt von der Anordnung der Daten ab. Gleiche Zeilen- und Spaltennummern allein begründen noch keine Interpretation. Zuerst muss klar sein, wofür beide Achsen stehen.

Lernen Sie mit Academia Master Trader auf academiamastertrader.com.br weiter. Unter Aprenda finden Sie Bildungsinhalte. Notieren Sie Form, Achsen und Versatz, markieren Sie die beteiligten Einträge und addieren Sie erst danach. Damit bleibt jede Summe mit ihren tatsächlichen Beiträgen verbunden.

NumPy diagonal selects a diagonal of entries rather than adding them or building a new matrix

A matrix contains several useful paths through its entries. A row follows one direction, a column follows another, and a diagonal advances along both selected axes at once. NumPy diagonal returns the entries on a specified diagonal. It does not add them together or automatically turn them into a new square matrix.

Academia Master Trader offers this English-language lesson for readers in Ireland. The numbers are invented to explain array positions, offsets and shapes. They are not market prices, trading signals or financial results. The aim is to connect each returned value to a clear position in the original array before giving the output any further meaning.

Reading the main diagonal

Consider a matrix a whose rows are [2,5,8], [11,14,17] and [20,23,26]. The expression np.diagonal(a) returns [2,14,26]. These values occupy positions (0,0), (1,1) and (2,2). The row index and the column index increase together along the main diagonal.

The input shape is (3,3), while the output shape is (3,). The result contains three selected values, not all nine entries. The values themselves are unchanged. Fourteen is returned because of its position in the matrix, not because it was calculated from the values around it.

Original diagram showing NumPy diagonal selecting 2, 14 and 26 from a three by three matrix

Keeping selection separate from addition

For this example, adding the selected values would give 42. That is a different operation from returning [2,14,26]. The documentation lists trace as a related function that sums along diagonals. A reader should therefore be told whether the intended result is a sequence of entries or one combined number.

This distinction also changes the shape of the output. A one-dimensional array with three values preserves the individual diagonal entries. A sum removes that detail. If later work needs the entries separately, replacing selection with addition changes the information available for that work.

Moving above the main diagonal

The offset argument chooses a diagonal relative to the main one. With np.diagonal(a,offset=1), the result is [5,17]. These values occupy positions (0,1) and (1,2). For this two-dimensional array, the positive offset moves the selected path above the main diagonal.

The output is shorter because this path reaches the edge after two entries. Using offset=2 gives [8], the single entry at position (0,2). The offset is a positional instruction. It is not a value added to the entries and does not mean that every output should have the same length.

Moving below the main diagonal

With np.diagonal(a,offset=-1), the result is [11,23]. The selected positions are (1,0) and (2,1). A negative offset selects below the main diagonal for the usual row and column axes. With offset=-2, only the entry 20 remains on the chosen path.

The sign changes which path is selected, not the signs of the stored numbers. Eleven does not become negative when the offset is negative. Writing down the selected positions beside the values is a simple way to keep those two meanings separate.

Rectangular arrays also have diagonals

A square input is not required. Suppose b has the rows [2,5,8] and [11,14,17]. Its shape is (2,3). The expression np.diagonal(b) returns [2,14], because the main diagonal cannot continue after the second row. The output shape is (2,).

For the same b, offset=1 returns [5,17]. An offset of -1 returns [11]. The available row and column positions jointly determine the length. A diagonal does not invent another row to match the number of columns, nor does it fill missing positions with zeros.

Naming the axes for higher-dimensional input

The arguments axis1 and axis2 identify the two axes used to form the plane from which diagonals are taken. Their default values are 0 and 1. When the input has more than two dimensions, leaving these defaults in place may select a different plane from the one a reader expects.

The documentation explains the output shape by removing those two selected axes and appending a new final axis for the diagonal entries. Other dimensions remain. For example, an array with shape (4,3,3), using axis1=1 and axis2=2 with the main diagonal, has output shape (4,3). Four separate three by three planes each contribute three entries.

Not confusing the main and opposite diagonals

In the original three by three example, the path from the upper-right corner to the lower-left corner contains [8,14,20]. That is not what np.diagonal(a) returns by default. The default path begins at the upper-left corner and moves through [2,14,26].

The documentation shows that reversing a matrix horizontally or vertically before selecting a diagonal can produce the opposite diagonal, with the order depending on the reversal used. It is therefore useful to describe the starting corner and reading direction rather than calling every sloping path the same diagonal.

Making independent storage explicit

The current documentation describes a read-only view for the returned diagonal and discusses behaviour across NumPy versions. If you need an independent array to edit, use np.diagonal(a).copy() explicitly. This avoids relying on the returned selection being a separate writable copy of the data.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides educational content. Record the input shape, mark the offset and write down the selected positions. This connects every returned entry to its source without confusing a diagonal selection with a sum, a new matrix or a change to the stored values.

NumPy rot90 roda uma matriz por quartos de volta no plano definido pelos eixos

Rodar uma matriz não é o mesmo que alterar os seus números. NumPy rot90 reorganiza os elementos através de rotações de 90 graus num plano definido por dois eixos. O resultado permite observar os mesmos valores noutras posições. Numa matriz rectangular, um quarto de volta também troca o número de linhas com o número de colunas.

A Academia Master Trader apresenta esta explicação em português para leitores em Portugal. Os números são inventados para estudar matrizes, posições e eixos. Não representam cotações, sinais de mercado ou resultados financeiros. O objectivo é compreender a transformação geométrica dos dados sem atribuir aos valores um significado que o exemplo não contém.

Começar com uma matriz rectangular

Considere a matriz a com as linhas [2,5,8] e [11,14,17]. A sua forma é (2,3): duas linhas e três colunas. Por predefinição, np.rot90(a) aplica uma rotação de 90 graus no sentido contrário ao dos ponteiros do relógio. A saída tem as linhas [8,17], [5,14] e [2,11].

A forma passa a (3,2). Continuam a existir seis elementos, mas agora estão distribuídos por três linhas e duas colunas. O valor 8, inicialmente no canto superior direito, passa para o canto superior esquerdo. Seguir um canto ajuda a confirmar o sentido da rotação sem depender apenas da forma final.

Esquema próprio de uma matriz com duas linhas e três colunas rodada 90 graus com NumPy rot90

Ler o argumento k como quartos de volta

O argumento k indica quantas rotações de 90 graus são aplicadas. O valor predefinido é 1. Com np.rot90(a,k=2), a rotação total é de 180 graus e as linhas da saída são [17,14,11] e [8,5,2]. A forma volta a ser (2,3), embora a ordem dos elementos seja diferente.

Com k=4, completam-se quatro quartos de volta e os elementos regressam às posições iniciais. O número k não é um ângulo expresso directamente em graus. Escrever k=90 não significa pedir uma única rotação de 90 graus: significa pedir noventa quartos de volta.

Usar um valor negativo para o sentido oposto

A expressão np.rot90(a,k=-1) aplica um quarto de volta no sentido oposto ao comportamento predefinido. As linhas resultantes são [11,2], [14,5] e [17,8]. A forma é (3,2), tal como no caso de k=1, mas os valores ocupam posições diferentes.

O sinal negativo pertence à contagem das rotações. Não transforma 2 em -2 nem altera os sinais dos restantes números. Comparar as duas saídas mostra por que razão conhecer apenas a forma não basta para identificar o sentido da transformação.

Identificar o plano com axes

O argumento axes define os dois eixos do plano em que a rotação acontece. Os valores predefinidos são (0,1). Para uma matriz com duas dimensões, estes correspondem aos eixos das linhas e das colunas. Os dois eixos indicados têm de ser diferentes.

A ordem do par também conta. A documentação explica que np.rot90(a,k=1,axes=(1,0)) faz a rotação inversa de np.rot90(a,k=1,axes=(0,1)). A primeira destas expressões é equivalente a usar k=-1 com o par predefinido. Não basta, portanto, mencionar os dois números sem conservar a sua ordem.

Distinguir rotação e transposição

Uma transposição simples da matriz do exemplo daria as linhas [2,11], [5,14] e [8,17]. A forma seria igualmente (3,2), mas esta saída não é a mesma de np.rot90(a). Na rotação predefinida, as linhas são [8,17], [5,14] e [2,11].

A coincidência entre as formas pode esconder uma diferença na ordem dos elementos. Uma descrição rigorosa deve nomear a operação, o sentido e os eixos. Dizer apenas que a matriz passou de duas linhas para três não explica onde ficou cada valor.

Arrays com mais dimensões

Rot90 aceita uma entrada com duas ou mais dimensões. Num array com três dimensões, é possível escolher um plano como axes=(1,2). Nesse caso, a transformação actua nesse plano, em vez de assumir que os dois primeiros eixos são sempre os relevantes.

Antes de escolher o plano, registe o significado de cada dimensão no seu conjunto de dados. A função conhece os números dos eixos, mas não sabe se representam altura, largura ou outra organização. Esse significado tem de vir da estrutura dos dados e da explicação que os acompanha.

Uma vista rodada não é uma cópia independente

A documentação descreve a saída como uma vista rodada da entrada. Uma vista permite outra organização dos mesmos dados sem ser necessariamente uma cópia independente. Quando a entrada é um array NumPy, uma alteração através da vista pode reflectir-se no array original.

Se precisar de uma cópia independente depois da rotação, pode usar .copy() no resultado. A disposição dos elementos mantém-se, mas a relação de partilha dos dados muda. Esta escolha deve ficar separada da escolha do ângulo: uma diz respeito à memória e a outra à posição dos valores.

Continue a aprender com a Academia Master Trader em academiamastertrader.com.br. Em Aprenda encontra conteúdo educativo. Anote a forma inicial, escolha um canto para acompanhar e indique k e axes. Assim, cada quarto de volta fica ligado a uma transformação clara, sem confundir rotação, transposição e mudança de valor.

NumPy roll desplaza los elementos de forma circular sin cambiar la forma del array

Desplazar una secuencia puede significar cosas distintas. A veces se eliminan los valores que salen por un extremo y se dejan posiciones vacías. NumPy roll aplica otra regla: los elementos que rebasan el final vuelven a entrar por el principio. El resultado conserva la forma del array y contiene los mismos elementos en posiciones diferentes.

Academia Master Trader presenta esta explicación en español para lectores de España. Los números son inventados y sirven para estudiar posiciones y ejes. No son cotizaciones, señales de mercado ni resultados financieros. El objetivo es comprender el desplazamiento circular antes de atribuir un significado a la nueva posición de cada valor.

Seguir un desplazamiento de una posición

Tomemos x=[2,5,8,11]. La expresión np.roll(x,1) produce [11,2,5,8]. El último elemento pasa al principio y los otros avanzan una posición. La longitud sigue siendo cuatro. No aparece un valor nuevo ni se pierde el que estaba situado al final.

El número 1 indica el desplazamiento, no una cantidad que se sume a los elementos. El 2 no se convierte en 3: conserva su valor y cambia de posición. Distinguir valor y posición evita confundir una transformación del orden con una operación aritmética sobre los datos.

Esquema propio con un desplazamiento circular de una posición en un array de cuatro elementos mediante NumPy roll

Entender los desplazamientos negativos

Con np.roll(x,-1), la salida es [5,8,11,2]. Ahora el primer elemento reaparece al final y los demás se mueven en el sentido contrario al desplazamiento positivo. El signo pertenece al argumento del desplazamiento; no cambia el signo de los valores almacenados.

Para esta secuencia, np.roll(x,2) da [8,11,2,5]. Si el desplazamiento es cuatro, la secuencia vuelve a su orden inicial. El comportamiento es circular: recorrer todas las posiciones de este eje devuelve cada elemento a su lugar de partida. Un desplazamiento mayor puede incluir varias vueltas completas.

Una matriz necesita una dirección explícita

Consideremos a con las filas [2,5,8] y [11,14,17]. Su forma es (2,3), dos filas y tres columnas. Indicar un eje permite definir qué posiciones participan en cada ciclo. El eje 0 recorre las filas y el eje 1 recorre las columnas dentro de cada fila.

La forma se conserva en los dos casos, pero las salidas no son iguales. Antes de leer una matriz desplazada, conviene anotar la forma de entrada, el desplazamiento y el eje. Esos tres datos permiten reconstruir el movimiento sin deducirlo únicamente a partir de la apariencia de la tabla.

Desplazar las filas con el eje 0

La expresión np.roll(a,1,axis=0) produce las filas [11,14,17] y [2,5,8]. La última fila pasa a la primera posición. Dentro de cada fila, los tres valores mantienen su orden. El ciclo tiene dos posiciones porque hay dos filas en ese eje.

En este ejemplo concreto, un desplazamiento de -1 por el eje 0 produce el mismo resultado que uno de 1. Esto ocurre porque el eje solo tiene longitud dos. No significa que los desplazamientos positivos y negativos sean siempre equivalentes: la longitud del eje y el número de posiciones determinan esa coincidencia.

Desplazar dentro de las filas con el eje 1

Con np.roll(a,1,axis=1), las filas resultantes son [8,2,5] y [17,11,14]. El último valor de cada fila vuelve al principio de esa misma fila. No salta a otra fila. Cada ciclo tiene tres posiciones y se aplica de forma independiente dentro de su fila.

Si el desplazamiento pasa a -1, las filas son [5,8,2] y [14,17,11]. Comparar ambas salidas muestra la importancia del signo. La forma (2,3) no cambia, pero la posición de cada elemento depende tanto del sentido como del eje elegido.

Leer el comportamiento sin eje

Cuando no se indica axis, NumPy aplana el array antes de desplazarlo y después restaura su forma original. Para la matriz del ejemplo, np.roll(a,1) produce las filas [17,2,5] y [8,11,14]. El ciclo recorre los seis elementos, no cada fila por separado.

El 17 pasa al principio de la secuencia aplanada. El 8, que estaba al final de la primera fila, acaba al principio de la segunda al restaurar la forma. Por eso omitir el eje puede mezclar posiciones entre filas aunque la salida siga teniendo dos filas y tres columnas.

Combinar ejes sin cambiar su identidad

El argumento shift admite una tupla cuando axis también contiene una tupla del mismo tamaño. Cada desplazamiento corresponde al eje situado en la misma posición de esa lista. Si se proporciona un solo entero junto con varios ejes, ese mismo desplazamiento se aplica a todos ellos.

Por ejemplo, np.roll(a,(1,1),axis=(0,1)) da las filas [17,11,14] y [8,2,5]. Las filas se desplazan una posición y los valores dentro de ellas también. Esto no intercambia los ejes: cambia posiciones a lo largo de ejes que conservan su identidad y su longitud.

Separar circularidad y significado

Roll reorganiza los elementos, pero no decide qué relación deben representar los extremos de una secuencia. Si el primer registro y el último tienen significados distintos, reunirlos mediante un ciclo requiere una justificación propia del problema. La función describe el movimiento de posiciones, no su interpretación.

Sigue aprendiendo con Academia Master Trader en academiamastertrader.com.br. En Aprenda encontrarás contenido educativo. Escribe el orden inicial, marca el eje y sigue un elemento hasta su nueva posición. Así podrás distinguir un desplazamiento circular de una suma, una inversión completa o un cambio de forma.

NumPy flip keert de volgorde langs een as om zonder de vorm van de array te veranderen

Een array heeft een vorm en een volgorde. Die twee eigenschappen zijn met elkaar verbonden, maar betekenen niet hetzelfde. NumPy flip draait de volgorde van elementen langs gekozen assen om. Het aantal posities langs elke as blijft gelijk. De waarden krijgen een andere plaats binnen dezelfde vorm.

Academia Master Trader biedt deze Nederlandstalige uitleg aan voor lezers in Suriname. De getallen zijn bedacht om de werking van arrays zichtbaar te maken. Ze zijn geen marktprijzen, handelssignalen of financiële resultaten. Het doel is om een omkering van de volgorde te onderscheiden van een verandering van vorm of een berekening met de waarden.

Beginnen met vier elementen

Neem x=[2,5,8,11]. De uitdrukking np.flip(x) levert [11,8,5,2] op. Het laatste element komt vooraan, het voorlaatste volgt daarna en het eerste element staat achteraan. De vorm blijft (4,). Er worden geen elementen toegevoegd of verwijderd.

De getallen veranderen zelf niet. Elf wordt geen ander getal en twee wordt niet vermenigvuldigd. Alleen de koppeling tussen een positie en een waarde verandert. Dat onderscheid helpt wanneer je een nieuwe volgorde moet uitleggen zonder er een nieuwe meting of berekening van te maken.

Eigen schema met vier waarden waarvan NumPy flip de volgorde omkeert terwijl de vorm gelijk blijft

Een matrix maakt de as belangrijk

Gebruik nu een array a met de rijen [2,5,8] en [11,14,17]. Deze array heeft de vorm (2,3): twee rijen en drie kolommen. Bij een matrix moet je aangeven welke richting wordt omgekeerd. As 0 loopt door de rijen, terwijl as 1 binnen de rijen langs de kolommen loopt.

Beide richtingen hebben een eigen betekenis. Het omkeren van de rijvolgorde verplaatst hele rijen. Het omkeren langs de kolommen verandert de volgorde binnen elke rij. De vorm alleen vertelt dus niet welke waarden op een bepaalde positie terechtkomen. Daarvoor is ook de gekozen as nodig.

As 0 keert de rijvolgorde om

Met np.flip(a,axis=0) worden de rijen [11,14,17] en [2,5,8]. De onderste rij van de invoer staat nu bovenaan. Binnen elke rij blijft de volgorde van links naar rechts hetzelfde. De vorm is nog steeds (2,3), omdat er twee rijen van elk drie elementen zijn.

Lees de eerste kolom afzonderlijk om dit na te gaan. Daar verandert [2,11] in [11,2]. In de tweede kolom verandert [5,14] in [14,5]. De derde kolom volgt dezelfde regel. De omkering gebeurt langs as 0, niet door de getallen op grootte te ordenen.

As 1 keert elke rij om

Met np.flip(a,axis=1) worden de rijen [8,5,2] en [17,14,11]. De eerste rij blijft de eerste rij, maar de drie posities erin worden in omgekeerde volgorde gelezen. De tweede rij krijgt op dezelfde manier een omgekeerde interne volgorde.

Ook hier blijft de vorm (2,3). Vergelijk dit resultaat met de omkering langs as 0: dezelfde invoer en dezelfde vorm geven verschillende uitkomsten. De naam van de functie is daarom niet genoeg om het resultaat te beschrijven. Noteer ook welke as bij de bewerking hoort.

Zonder as worden alle assen omgekeerd

Wanneer je np.flip(a) schrijft zonder een as te kiezen, worden standaard alle assen omgekeerd. Voor de voorbeeldmatrix geeft dat de rijen [17,14,11] en [8,5,2]. Zowel de rijvolgorde als de volgorde binnen elke rij is omgekeerd. De vorm blijft ook in dit geval (2,3).

Dit is niet hetzelfde als het verwisselen van rijen en kolommen. Bij zo'n verwisseling kan de vorm (3,2) worden. Flip behoudt juist de bestaande vorm. Het is ook geen sorteerbewerking: een invoer met een onregelmatige volgorde wordt simpelweg achterstevoren gelezen langs de gekozen assen.

Meerdere assen en negatieve asnummers

Het argument axis kan een tuple met meerdere assen bevatten. Voor deze matrix geeft np.flip(a,axis=(0,1)) dezelfde omkering als np.flip(a), omdat de matrix precies die twee assen heeft. Bij arrays met meer dimensies maakt een gekozen groep assen het mogelijk om andere assen ongemoeid te laten.

Een negatief asnummer telt vanaf de laatste as terug. As -1 is de laatste as. Bij de voorbeeldmatrix komt dat overeen met as 1. Het is nuttig om eerst de vorm en het aantal dimensies te noteren, zodat een negatief nummer niet wordt verward met een omkering van het teken van de waarden.

Een view delen is iets anders dan kopiëren

De documentatie beschrijft de uitvoer van flip als een view van de invoer met omgekeerde volgorde. Een view is geen zelfstandige kopie van alle gegevens. Bij een NumPy-array kan een wijziging via de view daarom zichtbaar worden in de oorspronkelijke array. Houd dat verschil apart van de visuele volgorde.

Wie een zelfstandige array nodig heeft, kan na de omkering expliciet een kopie maken met .copy(). De volgorde in die kopie is hetzelfde als in de omgekeerde view, maar het delen van de onderliggende gegevens is anders. Kies dus bewust tussen een andere leesrichting en onafhankelijke opslag.

Leer verder met Academia Master Trader op academiamastertrader.com.br. Via Aprenda vind je educatieve inhoud. Schrijf de invoer op, benoem de as en vergelijk de posities voor en na de omkering. Zo blijft duidelijk wat verandert, de volgorde, en wat gelijk blijft, de vorm.

NumPy cumprod conserve les produits successifs au lieu de donner seulement le produit final

Un produit cumulé décrit une multiplication qui avance dans un ordre précis. À chaque position, NumPy cumprod conserve le résultat obtenu en multipliant les valeurs rencontrées depuis le début de la séquence. La sortie permet donc de suivre les étapes du calcul, au lieu de ne présenter que son résultat final.

Academia Master Trader propose cette leçon en français pour une lecture en Haïti. Les nombres sont inventés pour expliquer les tableaux et leurs axes. Ils ne représentent ni des prix, ni des signaux de marché, ni des résultats financiers. Le but est de distinguer chaque valeur d'entrée du produit cumulé qui lui correspond.

Construire le produit étape par étape

Prenons x=[2,3,4,2]. L'expression np.cumprod(x) donne [2,6,24,48]. Le premier résultat est 2. Le deuxième est 2×3=6. Le troisième est 6×4=24. Le dernier est 24×2=48. Chaque position de sortie inclut ainsi la valeur courante et toutes les valeurs précédentes de cette séquence.

La longueur reste égale à quatre. Il n'y a pas un seul résultat, mais quatre produits successifs. Écrire les étapes aide à comprendre ce que signifie la deuxième position : 6 n'est pas la deuxième valeur d'entrée, qui vaut 3. C'est le produit des deux premières valeurs.

Schéma original présentant quatre valeurs et les quatre produits successifs calculés avec NumPy cumprod

Distinguer multiplication et addition

Pour le même x, une somme cumulée donnerait [2,5,9,11]. Ce n'est pas le calcul effectué par cumprod. Le mot produit désigne ici la multiplication. Confondre les deux opérations peut donner une sortie de la bonne longueur, mais dont chaque valeur répond à une autre question.

Dans une explication, préciser l'opération est donc aussi important que nommer la fonction. Une colonne de produits cumulés ne doit pas être présentée comme une colonne de contributions individuelles. Les positions se correspondent, mais le sens des valeurs est différent dès que plusieurs entrées participent au calcul.

Lire le comportement par défaut sur une matrice

Soit a une matrice dont les lignes sont [2,3] et [4,5]. Sa forme est (2,2). Sans axe indiqué, np.cumprod(a) travaille sur le tableau aplati. La séquence lue est 2,3,4,5 et la sortie est [2,6,24,120]. Le résultat est un tableau à une dimension contenant quatre valeurs.

Le calcul ne recommence pas au début de la deuxième ligne de la matrice d'origine. La valeur 4 multiplie le produit précédent, 6, pour donner 24. Comprendre ce passage entre les lignes permet de distinguer le comportement par défaut d'un calcul indépendant dans chaque ligne.

Choisir l'axe 1 pour chaque ligne

L'expression np.cumprod(a,axis=1) donne les lignes [2,6] et [4,20]. Le calcul avance dans la direction des colonnes, séparément pour chaque ligne. La première ligne commence à 2 et multiplie ensuite par 3. La deuxième commence à 4 et multiplie ensuite par 5.

La forme reste (2,2). Le produit final de la première ligne n'est pas transmis au début de la deuxième. Nommer l'axe et préciser où le calcul recommence explique pourquoi cette sortie diffère du résultat obtenu après aplatissement du tableau.

Choisir l'axe 0 pour chaque colonne

Avec np.cumprod(a,axis=0), les lignes de sortie sont [2,3] et [8,15]. Chaque colonne possède son propre calcul. Dans la première colonne, 2×4 donne 8. Dans la deuxième, 3×5 donne 15. Les valeurs de la première ligne constituent les produits initiaux de ces deux séquences.

La forme reste encore (2,2), mais les valeurs diffèrent du calcul par ligne. Une forme identique ne suffit donc pas à décrire une opération. Pour expliquer le résultat, il faut aussi indiquer la direction suivie et les valeurs qui participent à chaque produit.

Comprendre le rôle du zéro et des signes

Dans une séquence de nombres entiers signés, un zéro rend nul le produit cumulé à partir de sa position. Par exemple, [2,3,0,5] produit [2,6,0,0]. Le zéro est multiplié par la valeur suivante, il ne disparaît pas du calcul lorsque la lecture continue.

Les signes comptent également. Pour [2,-3,4], les produits sont [2,-6,-24]. Une multiplication par une valeur négative change le signe du produit non nul. Le caractère cumulé ne signifie donc pas que les résultats augmentent ou restent positifs. Il décrit la suite des multiplications.

Garder le type numérique visible

Le paramètre dtype permet de choisir le type du résultat et de l'accumulateur. La documentation de NumPy décrit aussi une promotion par défaut pour certains types entiers plus petits que l'entier habituel de la plateforme. Le type choisi doit convenir aux valeurs que les multiplications peuvent produire.

Pour les entiers, la documentation précise que l'arithmétique est modulaire et qu'un dépassement de capacité ne déclenche pas d'erreur. Il faut donc distinguer le calcul mathématique attendu de ce que le type numérique peut représenter. Un produit qui grandit rapidement mérite une attention particulière à ce choix.

Poursuivez votre apprentissage avec Academia Master Trader sur academiamastertrader.com.br. Aprenda donne accès au contenu pédagogique. Notez l'ordre des entrées, choisissez l'axe et écrivez chaque multiplication avant de lire la sortie. Cette méthode relie chaque produit à ses facteurs sans le confondre avec une nouvelle observation.

NumPy cumsum keeps every running total rather than returning only one final sum

A running total describes what has accumulated up to each position in a sequence. NumPy cumsum returns those cumulative sums. Its output keeps the intermediate totals, so a reader can follow how the result changes as each input entry joins the accumulation. It is different from asking only for one final total.

Academia Master Trader presents this lesson for English-language study in Saint Vincent and the Grenadines. All values below are invented teaching numbers. They are not prices, balances, trading signals or financial results. The examples explain array order, axis choice and output shape before considering what an accumulated value might represent.

Build the total one entry at a time

Let x be [4,3,-2,6]. The expression np.cumsum(x) returns [4,7,5,11]. The first total is 4. Adding the next entry, 3, gives 7. Adding -2 gives 5, and adding 6 gives 11. Each output position includes the input entry at that position and all preceding entries in this sequence.

A cumulative sum does not have to increase at every step. The negative input entry reduces the running total from 7 to 5. Calling an output cumulative explains how it was calculated, not whether its values must rise. The sign and magnitude of each added entry determine the next total.

Original diagram showing four input entries and the four running totals produced by NumPy cumsum

Preserve the distinction between entries and totals

The input entries and output totals answer different questions. The input value 3 describes one contribution in this example. The output value 7 describes the accumulation of the first two contributions. They occupy corresponding positions, but they do not have the same meaning.

This difference matters in labels and captions. A table headed only values can hide whether a column contains individual contributions or running totals. Name the cumulative column explicitly and state the order in which the contributions were accumulated. A running total depends on the sequence leading to that position.

Read the default matrix behaviour carefully

Let a contain rows [2,5] and [8,11], with shape (2,2). When no axis is supplied, np.cumsum(a) accumulates over the flattened array. The reading sequence is 2,5,8,11, and the output is [2,7,15,26]. The result is one-dimensional, with four entries.

The accumulation does not restart when the reading sequence crosses the original row boundary. The third total is 2+5+8=15, not simply 8. Omitting an axis therefore expresses a different operation from computing an independent running total inside each row of the original matrix.

Set axis 1 for separate row accumulations

The expression np.cumsum(a,axis=1) returns rows [2,7] and [8,19]. Within each row, the accumulation follows the column direction. The first row starts with 2 and then adds 5. The second row starts separately with 8 and then adds 11.

The output keeps shape (2,2). Each row contains its own sequence of running totals. There is no step that adds the final total of the first row to the beginning of the second. Stating where the accumulation restarts helps explain why these values differ from the flattened result.

Set axis 0 for separate column accumulations

For np.cumsum(a,axis=0), the output rows are [2,5] and [10,16]. The first row provides the initial totals for each column. The second row contains 2+8=10 in the first column and 5+11=16 in the second column. Again, the output shape remains (2,2).

Read each column as its own ordered sequence. Selecting axis 0 does not combine all columns into a single total. It describes the direction of accumulation while preserving the other positions. Comparing the flattened, axis 1 and axis 0 outputs makes the role of the axis visible.

Choose a numerical type that fits the accumulation

NumPy cumsum uses an accumulator whose type can be set with dtype. The documentation describes a default promotion for integer inputs narrower than the platform's default integer. That default is useful to know, but it is not a reason to ignore the scale of values that may be accumulated.

Integer arithmetic is modular when overflow occurs, and the documentation says no error is raised for that overflow. Floating-point accumulation has different concerns: rounding can affect the final value. Choose the numerical type with the calculation's range and precision in mind rather than assuming every running total is exact.

Separate a running path from one final result

For floating-point values, the final entry of cumsum may differ slightly from a separate sum calculation. NumPy's documentation explains that sum may use a pairwise summation routine, reducing rounding error. The two expressions can follow different numerical accumulation paths even when their mathematical total is described by the same addition.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Write the contribution order, select the axis and label each output as a running total. Those steps make the accumulation clear without confusing a larger cumulative value with a new individual contribution.

NumPy diff calculates consecutive differences rather than percentage changes or distances

A difference describes a subtraction in a particular order. NumPy diff calculates consecutive differences along a chosen array axis. For the first difference, each output entry is the next input entry minus the current input entry. The order matters: reversing the subtraction would change its sign.

Academia Master Trader presents this lesson for English-language study in Saint Kitts and Nevis. The examples use invented numbers for array study, not market prices, trading signals or financial results. The purpose is to connect each output entry with the pair of input positions that produced it, before assigning any wider meaning to the result.

Follow one neighbouring pair at a time

Let x be [3,8,6,13]. The expression np.diff(x) returns [5,-2,7]. The first calculation is 8-3=5, the second is 6-8=-2 and the third is 13-6=7. Four input entries provide three neighbouring pairs, so the output contains three entries.

The result is not a list of distances that are always positive. The middle difference is negative because the next value, 6, is smaller than the current value, 8. Keeping the subtraction order visible explains that sign without changing the calculation into an absolute difference.

Original diagram connecting four input entries to their three consecutive differences with NumPy diff

Keep subtraction separate from percentage change

The value 5 in the first output position is a difference in the same numerical units as the input values. The function has subtracted 3 from 8. It has not divided by a starting value, multiplied by one hundred or supplied a percentage. Those would be separate calculations requiring their own definitions.

Likewise, an ordinary difference is not automatically a rate per unit of time. If input positions correspond to observations, the timing between them matters when interpreting a rate. NumPy diff applies the subtraction rule to the supplied positions; its output alone does not establish equal observation intervals or a time unit.

Count pairs before reading the output shape

Along a nonempty sequence, a first difference uses adjacent pairs and reduces the length by one when no boundary values are added. For the four-entry x, the result has length three. There is no output entry corresponding to a pair before the first input position because no earlier value was supplied.

When aligning differences with labels, describe which pair each label represents. Assigning the first output to the second input position can be useful in some presentations, but that is a labelling choice to explain. The calculation itself links two input positions, not a new independent observation at an unspecified location.

Apply a second difference to the first result

The parameter n sets how many times the differencing operation is applied. For the same x, the first result is [5,-2,7]. Applying the rule again gives [-7,9], because -2-5=-7 and 7-(-2)=9. This is np.diff(x,n=2).

A second difference does not compare every input entry with the value two positions ahead using one subtraction. It calculates differences of differences. Writing the intermediate sequence makes that meaning clear and provides a direct way to check the signs. Each stage uses the result of the previous stage.

Choose an axis for a matrix

Let a contain rows [2,5,9] and [8,10,15]. With the default last axis, np.diff(a) calculates differences across each row. The output rows are [3,4] and [2,5]. The row count remains two, while the column count changes from three to two.

For np.diff(a,axis=0), the subtraction runs between neighbouring rows instead. The output is one row, [6,5,6], obtained by subtracting the first row from the second column by column. The shape is (1,3). The same input supports different questions depending on which axis is selected.

Explain any supplied boundary value

The prepend argument supplies values before differencing; append supplies values after the input. For example, np.diff(x,prepend=0) gives [3,5,-2,7]. The added zero creates an extra first pair, so the first difference is 3-0=3. The remaining differences match the original three-pair calculation.

That initial zero is an explicit construction choice, not a recovered earlier observation. State why it was used. Adding a boundary value can change the output length, but it also changes the question answered by the first or final difference. Preserving length is not, by itself, an explanation of the added pair.

Read the data type as part of the calculation

These examples use ordinary signed numerical values. NumPy's documentation notes that unsigned integer differences remain unsigned. A subtraction that would be negative in signed arithmetic can therefore have a different representation. When negative differences are needed, choose a suitable signed type before applying the operation.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Name the axis, write the next-minus-current subtraction for each pair and keep any boundary choice visible. That process explains the differences without treating them as percentages, rates or independent observations.

NumPy pad adds a defined border while keeping the original array entries together

Adding positions around an array is different from repeating its whole pattern or changing the arrangement of its existing entries. NumPy pad creates a padded array whose border follows a chosen rule. In constant mode, the added positions contain a specified constant, while the original entries remain together inside that border.

Academia Master Trader presents this lesson for English-language study in Saint Lucia. All numbers are invented teaching values, not prices, trading signals or financial results. The aim is to explain three separate choices: how many positions to add, which sides receive them and what values the added positions contain.

Read the width before choosing the value

Let x be [4,7,10]. The expression np.pad(x,(1,2),mode='constant') adds one position before the sequence and two positions after it. With the default constant value of zero, the output is [0,4,7,10,0,0]. Its length is six: three original positions plus three added positions.

The pair (1,2) describes widths, not the values written into the border. It does not place the number 1 before the array and the number 2 after it. Keeping the width separate from the border value makes the expression easier to explain and the output easier to check.

Original diagram showing one zero added before and two zeros after a three-entry array with NumPy pad

Recognise the constant mode explicitly

Constant is the default padding mode, and its default added value is zero. Writing mode='constant' in a lesson makes the intended rule visible even when the default would produce the same output. The widths determine how many positions are added; the mode determines how their values are supplied.

Other modes use other rules. Edge mode repeats boundary values, while wrap mode takes values from the opposite end of the array. A matching output shape does not mean that two modes produce matching contents. Name the mode alongside the widths whenever the border values matter to the explanation.

Choose a different border constant deliberately

Constant mode can use a value other than zero. In np.pad(x,(1,2),mode='constant',constant_values=9), the same three added positions contain 9. The output is [9,4,7,10,9,9]. The original sequence stays 4,7,10, and the output length stays six.

The parameter name constant_values contains an underscore. Read it as the setting for the values used in the constant border, not as a separate width. Changing that setting alone does not change the number of positions added. The border's content and its dimensions remain separate parts of the call.

Give each matrix axis its own width pair

Let a contain rows [2,5] and [8,11], with shape (2,2). For a matrix, axis 0 describes the row direction and axis 1 the column direction. The nested widths ((1,0),(0,1)) request one row before and none after along axis 0, then no columns before and one column after along axis 1.

With constant zero padding, np.pad(a,((1,0),(0,1)),mode='constant') produces rows [0,0,0], [2,5,0] and [8,11,0]. Its shape is (3,3). The original two-by-two block sits below the added top row and before the added final column. Its internal ordering has not changed.

Calculate the output shape from both sides

For each axis, add the original length, the width before and the width after. In the matrix example, the row length becomes 2+1+0=3 and the column length becomes 2+0+1=3. Calculating those lengths before writing the output gives a useful independent check on the arrangement.

A zero width means that no positions are added on that side. It does not create a border filled with zeros there. In the example, the final column contains zeros because constant mode fills an added column with its default value, not because one of the width settings happens to be zero.

Keep original entries distinct from supplied entries

If an array represents observations, padding does not create new observations. The border entries are supplied by a construction rule. A zero in that border can mean a chosen placeholder rather than a measured zero. Preserve that difference when labelling an output table or describing what its values represent.

The same care applies when a border constant happens to equal a value already inside the array. Equal numbers do not establish equal origins. A small diagram that marks the original region can show which entries came from the input and which were supplied by the padding rule.

Explain the complete border decision

A clear description names the input shape, each before-and-after width, the mode and any chosen constant. Then it identifies where the original block appears in the output. These details explain both the new shape and the meaning of its border without treating added positions as additional recorded data.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Start with one side of one axis, count the positions added there and follow the chosen filling rule. Repeat that reading for the remaining sides before interpreting the completed array.

NumPy resize fills a new shape by cycling through array entries rather than interpolating values

Changing an array's shape and changing its total number of entries are different operations. NumPy resize can return an array with a different total size. When the requested output needs more entries than the input contains, it cycles through the input again. The extra positions contain repeated existing values, not values calculated between neighbouring entries.

Academia Master Trader presents this lesson for English-language study in Grenada. The examples use invented numbers to explain array arrangement. They are not prices, trading signals or financial results. The central question is where each output position gets its value, especially when the output contains more positions than the original input.

Start with the input reading order

Let a have two rows, [2,5] and [8,11]. Its shape is (2,2), so it contains four entries. For np.resize, read this input in C-order: the last axis changes fastest. In this simple matrix, that means reading across the first row and then across the second row. The resulting sequence is 2,5,8,11.

Keep that sequence beside the requested output shape. The function fills output positions in that same order. It does not preserve the original row boundaries as independent units. A new row can therefore begin in the middle of the input sequence, depending on how many columns the output has.

Fill a larger output one position at a time

The expression np.resize(a,(2,3)) requests two rows and three columns, for six entries altogether. Reading the input gives only four entries. The function uses 2,5,8,11, then returns to the beginning and uses 2,5 again. Arranged into the requested shape, the output rows are [2,5,8] and [11,2,5].

Notice the boundary after the first three output entries. The original input row [2,5] has not been stretched into three smoothly changing values. Instead, the first entry from the second input row, 8, completes the first output row. The next output row starts with 11 before the cycle returns to 2.

Original diagram showing NumPy resize reading four entries in order and cycling back to fill a two-by-three output

Separate a new shape from new information

The six-position output contains two additional positions, but it contains no newly observed values. The values 2 and 5 appear again because the filling procedure returned to the start of the input. Their repeated appearance is a consequence of array construction, not evidence of additional measurements.

This distinction matters whenever a table represents observations rather than an abstract pattern. State why repeated entries exist. A larger array can be convenient for illustrating a layout, but its shape alone does not explain whether the entries were observed, calculated, copied or supplied as placeholders.

Read a smaller output as a shorter sequence

The expression np.resize(a,(1,3)) requests three entries. The output is one row, [2,5,8]. The value 11 is not needed to fill the requested positions. Reducing the output size does not summarise the four original values, preserve every row or calculate an average. It fills the smaller output from the start of the same reading sequence.

If the goal is to select particular rows or columns, describe that selection directly with indexing. A shorter output from resize follows its filling rule; it is not a statement that the omitted positions were unimportant. Name the intended data operation before choosing a function with a convenient output shape.

Use reshape when the total size stays the same

For the same four input entries, a shape such as (1,4) does not require extra positions or discard any entries. NumPy's documentation directs readers to reshape when the total size does not change. That choice makes the purpose clearer: rearranging the shape while keeping the number of entries fixed.

For a larger output, first decide how new positions should be filled. Repeating the input cycle, adding a chosen border value and estimating intermediate values are different aims. NumPy resize has one particular filling rule. Choosing it because its name resembles a general resizing operation can hide that rule from a reader.

Distinguish the function from the array method

The function call np.resize(a,newshape) returns a new array. It is different from the ndarray method a.resize(newshape), which changes an array in place when its conditions allow that change. The two forms also differ when enlarging: the method fills additional positions with zeros rather than cycling through the original values.

Read the complete expression, including whether resize follows np or follows an array variable. That small difference in notation changes the operation. In written explanations, name the function explicitly and show the input and output rather than relying on the word resize by itself.

Keep axis meanings in view

NumPy resize does not treat each axis as a separate entity and does not perform interpolation or extrapolation. Its cycling sequence can cross original row boundaries. The documentation therefore says it is not suitable for resizing images or data whose axes represent separate, distinct entities.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda opens the educational material. Write the input reading sequence, count the requested output positions and trace where the filling cycle returns to the start. Those steps explain the new array without confusing extra positions with extra information.