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 roll shifts array positions cyclically and brings displaced values back at the opposite end

Moving a sequence by one position can mean several different things. A program might discard a value, leave an empty position or bring the value back at the other end. NumPy roll uses the third rule. It shifts positions cyclically, so entries that pass beyond an end reappear at the opposite end rather than disappearing.

Academia Master Trader presents this explanation in English for readers in Uganda. The examples describe numerical array organisation only. They do not represent prices, trading signals or financial results. The aim is to understand where values move, how the chosen axis affects that movement and why a cyclic shift needs a clear interpretation.

One positive shift in a vector

Consider the vector [2,5,8,11]. The expression np.roll([2,5,8,11],1) produces [11,2,5,8]. Each value moves one position towards the end. The value eleven passes beyond the last position and returns at the first. The output still contains four values and has shape (4,).

The shift is a count of positions, not an amount added to the numbers. Two becomes the second entry; it does not become three. Likewise, the eleven at the beginning is the original last entry, not a new observation or a value calculated from the other three.

Original diagram: a positive shift of one moves eleven from the last position to the first while the remaining values move one place.

A negative shift changes the direction. The expression np.roll([2,5,8,11],-1) produces [5,8,11,2]. The first value moves beyond the beginning and returns at the end. Both directions preserve the input shape and the values present in the sequence.

Count positions around the cycle

A shift equal to the length of this four-element vector brings every value back to its starting position. A shift of four therefore produces [2,5,8,11] again. A shift of five has the same visible result as a shift of one because it includes one complete turn plus one extra position.

This relationship follows from the cyclic rule. It does not mean the operation sorts, groups or simplifies the values. The original order is preserved around the cycle, but the position chosen as the beginning changes. Repeated values can make that change harder to see, so distinct example numbers are useful when explaining the mapping.

Choose the direction within a matrix

Let x have rows [1,2,3] and [4,5,6], giving it shape (2,3). The expression np.roll(x,1,axis=0) produces rows [4,5,6] and [1,2,3]. The rows shift along the first axis. With only two rows, one positive step exchanges their positions.

For np.roll(x,1,axis=1), the rows become [3,1,2] and [6,4,5]. Each row is shifted along its columns. The last entry of each row returns at the beginning of that same row. Values do not move between rows in this axis-one example.

The output shape remains (2,3) for both choices. Axis specifies the dimension in which positions change. It does not select a particular numeric value and does not add a dimension to the result. Naming the direction in words makes the intended operation easier to review.

Without an axis, flattening comes first

The default behaviour is different from choosing axis zero. When axis is omitted, roll flattens the input before shifting and then restores the original shape. For the same matrix, np.roll(x,1) produces rows [6,1,2] and [3,4,5].

The flattened order starts as [1,2,3,4,5,6]. After a shift of one it is [6,1,2,3,4,5]. Restoring the two-by-three shape explains the resulting rows. In this case, a value can cross the boundary between rows because the shift took place in the flattened sequence.

The final matrix still has shape (2,3). Shape preservation does not mean that the default operation treats each row separately. The intermediate order matters. An explicit axis is useful when the program must keep the shift within a particular dimension.

Several axes can move together

Roll also accepts tuples for shift and axis. When both are tuples, the corresponding entries describe the shift for each selected axis. A single integer shift with a tuple of axes applies that same shift to all the listed axes. The mapping between these arguments should be written clearly when more than one direction is involved.

For an introductory explanation, it is often clearer to understand one axis at a time before combining them. Follow one distinctive value from its original coordinates to its final coordinates. That position-based description avoids confusing a cyclic shift with a reversal of the entire order.

A cyclic arrangement needs a reason

Bringing the last value back to the beginning is a structural rule, not proof that the underlying observations form a natural cycle. If positions represent a particular sequence, the program should explain why wrapping the end to the start is appropriate. Roll does not determine that meaning on its own.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the shape, the direction and the number of positions, then follow the entries that cross an end. This keeps cyclic movement distinct from addition, reversal and the creation of new data.

NumPy flip reverses the order along chosen axes while keeping the array shape unchanged

Changing the direction in which an array is read is different from sorting its values or exchanging its dimensions. NumPy flip reverses the order of entries along selected axes. The values move to different positions in that arrangement, but the shape of the array stays the same. Understanding which axis is reversed explains the result more clearly than the word flip alone.

Academia Master Trader presents this explanation in English for readers in Kenya. The examples concern numerical array structure only. They do not represent prices, trading signals or financial results. The aim is to separate the order of positions from the meaning of the numbers stored at those positions.

Reverse a single sequence

For the vector [2,5,8], the expression np.flip([2,5,8]) produces [8,5,2]. The last position is read first, the middle position remains in the middle and the first position is read last. Both the original vector and the result have shape (3,).

This is not an instruction to sort numbers from largest to smallest. The example happens to begin with increasing values, so its reverse looks like descending order. With [5,2,8], reversing gives [8,2,5], which is not descending order. Flip follows the original positions, not a ranking rule based on value.

A matrix has more than one direction

Let x be a matrix with rows [1,2,3] and [4,5,6]. Its shape is (2,3). The expression np.flip(x,axis=0) produces rows [4,5,6] and [1,2,3]. The two rows exchange their order, while the order of entries within each row remains unchanged.

The result still has two rows and three columns. Axis zero identifies the dimension whose positions are being reversed. It does not mean that the first value becomes zero or that a row is removed. The numeric axis label describes an organisational direction within the array.

Original diagram: reversing axis zero exchanges the two rows of a matrix and preserves shape two by three.

With np.flip(x,axis=1), the result instead has rows [3,2,1] and [6,5,4]. The order of columns is reversed within each row. The first row remains the first row. Shape (2,3) is preserved here too, even though different positions have changed compared with the axis-zero example.

The default reverses every axis

Calling np.flip(x) without an axis reverses all axes of the input. For the example matrix, the result has rows [6,5,4] and [3,2,1]. Both the row order and the column order have been reversed. This differs from reversing only one of the two axes.

It is therefore important not to read an omitted axis as an automatic choice of axis zero. The documented default is None, which selects all axes. An explicit axis can make the intention clearer when a program should reverse only one direction of a multidimensional array.

A tuple can also identify several axes. In a two-dimensional matrix, np.flip(x,axis=(0,1)) reverses both available axes. For arrays with more dimensions, a tuple can select a subset rather than all of them. Each selected axis is reversed without changing its length.

Reversal is not transposition

A transpose changes the positions of axes. A flip changes the direction of positions along an axis. In the example, every flip result remains shape (2,3). Transposing the original matrix would give shape (3,2). These operations should not be treated as interchangeable ways to change a matrix's appearance.

The distinction is easier to see with a rectangular matrix than with a square one. A square matrix can keep the same shape after transposition, even though its positions have been rearranged differently. Shape is useful evidence, but the actual mapping of positions is also needed to explain the operation.

A view is not an independent copy

For a NumPy array, flip returns a view with the selected axis directions reversed. A view can share the original data rather than storing a separate, independent set of values. A different displayed order does not by itself prove that new independent storage has been created.

This matters if the program later writes through that view. A change to shared data can also be visible through the original array. If independent storage is required, that intention should be expressed separately with an appropriate copy. Reading the reversed arrangement and changing its underlying data are different activities.

Keep the meaning of the order clear

Reversing observations does not create new observations or alter the source from which the values came. It changes their order in the array view. If positions represent a particular sequence, the program should document why reversing that sequence is appropriate before using it in a later calculation.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to educational material. Identify the input shape, name the axes being reversed and follow the resulting positions. This keeps reversal separate from sorting, transposition and copying.

NumPy stack joins equally shaped arrays along a new axis rather than extending an old one

Two arrays can contain matching sets of positions without belonging in one long sequence. Sometimes the useful result keeps each input together and adds a dimension that identifies which input supplied a value. NumPy stack performs that kind of join. It combines arrays along a new axis instead of extending an axis that already exists.

Academia Master Trader presents this explanation in English for readers in Ghana. The examples concern the structure of numerical arrays only. They do not represent market prices, trading signals or financial results. The aim is to make the relationship between input shapes, the new axis and the final arrangement easy to follow.

Two vectors become a matrix

Let a be the vector [1,2,3] and b the vector [4,5,6]. Each input has shape (3,). The expression np.stack((a,b),axis=0) produces a matrix whose rows are [1,2,3] and [4,5,6]. Its shape is (2,3).

The new first axis has length two because there are two input arrays. The original axis of length three remains present as the second axis. Each input was one-dimensional, and the result is two-dimensional. There are six elements in total, but the extra dimension is the main structural change.

Original diagram: stack joins two vectors of three values into a matrix with two rows and three columns.

The values are neither added nor averaged. The first row comes from a and the second from b because the inputs were supplied in that order. Reversing the sequence to (b,a) changes their order along the new axis. Stack does not select an order based on the values themselves.

Put the new axis last

With the same vectors, np.stack((a,b),axis=-1) produces the rows [1,4], [2,5] and [3,6]. The output shape is (3,2). The new axis now comes last, so each row brings together values from the same original position in the two inputs.

This arrangement still contains six elements. However, shape (3,2) is different from shape (2,3). One result has three rows and two columns; the other has two rows and three columns. Counting elements alone cannot tell a reader how the axes have been arranged.

For this two-dimensional result, axis one and axis minus one identify the same final axis. A negative axis index counts from the end of the result. It is helpful to describe the intended dimensions in words before choosing the numeric index, especially when the inputs have more than one dimension.

Every input must have the same shape

Stack requires the input arrays to have the same shape. A vector with shape (3,) does not match a matrix with shape (1,3), even though both contain three values. Their numbers of dimensions differ. The visible values alone do not establish compatibility.

Likewise, two vectors of lengths three and four do not meet the requirement. Stack does not invent a fourth value for the shorter vector. Any decision to pad, remove or otherwise reorganise values belongs to an earlier preparation step and needs a reason that comes from the data's intended use.

Shape equality is a structural condition, not proof of matching meaning. Two arrays may have the same shape while containing different units or referring to different periods. The function has no knowledge of those distinctions. Anyone preparing the inputs must decide whether corresponding positions should be grouped together.

Stacking matrices adds a third dimension

Suppose two inputs both have shape (2,3). Stacking them with axis zero produces shape (2,2,3). The first two in that shape records the number of inputs. The next two and the final three come from the two rows and three columns within each input.

Putting the new axis last instead produces shape (2,3,2). The new dimension still has length two, but its position in the shape changes. This is why axis is an instruction about where to insert a dimension, not merely a choice between placing items visually above or beside one another.

A useful check is to mark the new dimension separately when writing the expected shape. Then read the remaining dimensions in their original order. The number of dimensions should increase by one compared with each input, while the new dimension's length should equal the number of arrays supplied.

Contrast stack with concatenate

Concatenate joins along an existing axis. For the vectors [1,2,3] and [4,5,6], concatenation along axis zero produces [1,2,3,4,5,6], with shape (6,). Stack with axis zero instead produces shape (2,3). The two functions preserve the same example values but organise them differently.

The choice therefore starts with the intended structure. If the inputs should become sections of one existing dimension, concatenation may express that intention. If an additional dimension should identify the separate inputs, stack expresses a different relationship. Neither function decides what the added organisation means in the subject being studied.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda provides access to the educational material. Write down each input shape, identify where the new axis belongs and compare the output with that description. This keeps values, positions and dimensions separate throughout the join.

NumPy concatenate junta arrays ao longo de um eixo existente sem somar os seus valores

Juntar duas estruturas numéricas não significa somar os números que ocupam posições semelhantes. A função concatenate do NumPy reúne uma sequência de arrays ao longo de um eixo que já existe. A ordem das entradas, a escolha do eixo e a compatibilidade das formas determinam como os valores aparecem na saída.

A Academia Master Trader apresenta esta explicação em português para leitores de Timor-Leste. Os exemplos descrevem a organização de dados, sem representar cotações, sinais de negociação ou resultados financeiros. A proposta é acompanhar uma junção simples e distinguir o crescimento de uma dimensão da criação de um eixo novo.

Juntar duas matrizes pelas linhas

Considere a matriz a com as linhas [1,2] e [3,4], cuja forma é (2,2). Considere também a matriz b com uma única linha [5,6], cuja forma é (1,2). Ambas têm duas colunas, embora possuam quantidades diferentes de linhas.

A expressão np.concatenate((a,b),axis=0) produz três linhas: [1,2], [3,4] e [5,6]. A forma final é (3,2). O primeiro eixo aumentou de duas mais uma para três posições, enquanto o segundo permaneceu com duas posições. Os valores não foram somados nem ordenados por tamanho.

Figura própria: duas linhas da matriz a e uma linha da matriz b formam uma matriz com três linhas e duas colunas.

A sequência (a,b) indica quais arrays serão reunidos e em que ordem. O conteúdo de a aparece antes do conteúdo de b ao longo do eixo escolhido. Se a sequência das entradas mudar, a organização da saída também poderá mudar. A função não procura automaticamente uma ordem cronológica ou uma correspondência por nomes.

Compatibilidade fora do eixo escolhido

As formas podem ser diferentes na dimensão que recebe a junção. Nas restantes dimensões, têm de ser compatíveis pela igualdade dos tamanhos. No exemplo, o número de linhas pode variar porque a junção ocorre no eixo zero. As duas colunas precisam de corresponder em quantidade.

Uma matriz com duas colunas não pode ser simplesmente concatenada pelas linhas com outra que tenha três colunas. É necessário esclarecer primeiro qual é a estrutura pretendida. A função não preenche automaticamente uma coluna em falta nem decide quais valores deveriam ser acrescentados. A compatibilidade faz parte da preparação dos dados.

Também convém separar a forma do significado. Duas tabelas podem ter a mesma quantidade de colunas e ainda assim representar campos diferentes. A função trabalha com posições numéricas. Cabe a quem organiza os dados garantir que as colunas reunidas têm a interpretação adequada ao uso posterior.

Juntar pelas colunas

Para juntar ao longo do eixo um, a quantidade de linhas deve coincidir. Retome a matriz a de forma (2,2) e considere uma matriz c com as linhas [5] e [6], de forma (2,1). A expressão np.concatenate((a,c),axis=1) produz as linhas [1,2,5] e [3,4,6].

A forma final é (2,3). O número de linhas mantém-se em dois, enquanto as duas colunas de a se juntam à coluna de c. O resultado tem seis elementos, tal como o exemplo de três linhas por duas colunas. A igualdade na contagem total não torna as duas formas equivalentes.

Antes da operação, escreva a forma de cada entrada e identifique a dimensão que vai crescer. Depois confirme que as restantes dimensões são iguais. Esta sequência de leitura é mais clara do que tentar deduzir o eixo apenas a partir da forma visual da matriz impressa.

Um eixo existente não é um eixo novo

Concatenate prolonga um eixo existente. Não cria por si só uma dimensão adicional para guardar cada entrada numa camada separada. A função stack tem essa outra finalidade, ao reunir arrays ao longo de um eixo novo. As duas operações respondem a perguntas diferentes sobre a organização pretendida.

Para dois vetores [1,2] e [3,4], concatenar ao longo do eixo zero produz o vetor [1,2,3,4], de forma (4,). Não produz automaticamente duas linhas de dois valores. A intenção de criar uma matriz precisa de ser expressa pela operação apropriada, não inferida da presença de duas entradas.

Achatar antes de juntar

Quando axis recebe None, concatenate achata as entradas antes da junção. Para as matrizes a e b do primeiro exemplo, np.concatenate((a,b),axis=None) produz [1,2,3,4,5,6]. A saída é unidimensional e tem forma (6,).

Esta opção altera a organização das dimensões que se vê no resultado. Os valores continuam presentes, mas já não estão distribuídos pelas três linhas da primeira junção. Por isso, convém escolher conscientemente entre conservar os eixos e reunir todos os elementos numa sequência única.

Juntar estruturas não valida a origem

A função não determina se as entradas foram recolhidas no mesmo período ou se possuem unidades equivalentes. Uma junção tecnicamente possível pode exigir revisão do contexto. Registar a origem e a ordem das entradas permite interpretar o array final sem atribuir à função verificações que ela não realiza.

Continue a aprender com a Academia Master Trader em academiamastertrader.com.br. Aprenda dá acesso aos conteúdos educativos. Identifique as formas, escolha o eixo e acompanhe a ordem das entradas. Assim, cada posição da saída pode ser relacionada com a estrutura de onde veio, sem confundir junção, soma e criação de dimensões.

NumPy tile repete um bloco de valores e organiza as cópias ao longo dos eixos

Uma sequência pode voltar a aparecer como um bloco completo ou ter cada um dos seus elementos repetido separadamente. São duas regras diferentes. A função tile do NumPy constrói uma saída repetindo a estrutura fornecida de acordo com as quantidades indicadas em reps. Para compreender o resultado, é preciso acompanhar a ordem dos valores e a forma do array.

A Academia Master Trader apresenta esta explicação em português para leitores da Guiné-Bissau. Os exemplos tratam apenas da organização de dados numéricos. Não representam cotações, sinais de negociação ou resultados financeiros. A proposta é distinguir repetição de blocos, repetição de elementos e expansão de dimensões antes de utilizar estas estruturas noutros cálculos.

Um vetor repetido como bloco

Considere a sequência [2,5,8]. A expressão np.tile([2,5,8],2) produz [2,5,8,2,5,8]. A sequência completa aparece duas vezes, mantendo a ordem dos seus três valores em cada ocorrência. O resultado tem seis elementos e forma (6,).

O argumento dois indica duas ocorrências do bloco no total. Não significa duas cópias adicionais além de uma primeira ocorrência. A entrada tem três posições e a saída tem três vezes duas, ou seja, seis. Esta contagem deve ser feita a partir da regra da função, em vez de interpretar a palavra repetição como uma adição implícita.

Figura própria: tile apresenta duas ocorrências consecutivas do bloco dois, cinco, oito.

A saída não é [2,2,5,5,8,8]. Essa disposição coloca as ocorrências de cada elemento lado a lado. No exemplo de tile, as fronteiras do bloco são diferentes: depois do primeiro oito, a sequência recomeça no dois. Ambas as saídas têm seis posições, mas a ordem não é a mesma.

Acrescentar uma dimensão pela repetição

Com a mesma entrada, np.tile([2,5,8],(2,1)) produz duas linhas iguais a [2,5,8]. A forma do resultado é (2,3). O vetor original tem um eixo. Como reps descreve dois eixos, a função considera a entrada com uma dimensão inicial de tamanho um, antes de aplicar as quantidades de repetição.

É útil escrever essa passagem em duas etapas conceituais: a forma (3,) é considerada como (1,3) e depois recebe as repetições (2,1). A primeira dimensão passa de um para dois; a segunda permanece com três posições. Esta descrição explica a matriz obtida sem confundir a quantidade de eixos com a quantidade total de elementos.

Se usarmos np.tile([2,5,8],(2,2)), cada uma das duas linhas contém [2,5,8,2,5,8]. A forma passa a ser (2,6). Existem duas repetições na direção das linhas e duas na direção das colunas, depois de a entrada ser considerada bidimensional.

Repetir uma matriz existente

Imagine agora uma matriz x com as linhas [1,2] e [3,4]. A expressão np.tile(x,(2,1)) produz quatro linhas: [1,2], [3,4], [1,2] e [3,4]. O bloco de duas linhas foi repetido duas vezes. A forma final é (4,2).

Já np.tile(x,(1,2)) produz as linhas [1,2,1,2] e [3,4,3,4], com forma (2,4). Neste caso, o bloco é repetido ao longo das colunas. A ordem de reps corresponde à ordem dos eixos. Não se trata de uma indicação livre de quantas linhas ou colunas se pretende na saída.

As quantidades são fatores de repetição. Uma matriz de duas linhas com reps igual a (2,1) termina com quatro linhas, não com duas. Para acompanhar uma expressão, escreva primeiro a forma original e multiplique cada dimensão pelo fator correspondente, depois de compatibilizar o número de eixos.

Quando reps tem menos eixos

Se a entrada já for uma matriz e reps for apenas dois, a função considera os fatores necessários à esquerda como um. Assim, para a matriz de forma (2,2), np.tile(x,2) corresponde ao comportamento de reps igual a (1,2). O resultado tem forma (2,4).

Este pormenor evita a ideia de que um único número repete sempre a matriz inteira na direção das linhas. A posição desse fator em relação aos eixos importa. Quando a intenção precisa de ficar clara para quem lê o código, escrever todos os fatores de reps pode tornar a organização pretendida mais explícita.

Uma estrutura maior não contém mais observações de origem

Repetir um bloco aumenta o número de posições no resultado, mas não cria novas recolhas de dados. Se uma sequência veio de três observações, apresentá-la duas vezes continua a reutilizar essas mesmas três observações. O contexto deve explicar por que motivo as ocorrências repetidas são necessárias.

A documentação do NumPy também distingue tile das operações de broadcasting. Quando o objetivo é apenas permitir uma operação entre formas compatíveis, recomenda recorrer às operações próprias de broadcasting. Conhecer tile não implica que duplicar materialmente a estrutura seja a escolha adequada para qualquer cálculo.

Continue a aprender com a Academia Master Trader em academiamastertrader.com.br. Aprenda dá acesso aos conteúdos educativos. Identifique o bloco original, escreva os fatores de repetição e confirme a forma final. Assim, a ordem dos valores e a origem da informação permanecem claras, mesmo quando a estrutura passa a ocupar mais posições.

NumPy repeat repete cada elemento e distingue essa operação da repetição de um bloco inteiro

Repetir valores numa estrutura numérica exige uma pergunta precisa: pretende repetir cada elemento ou voltar a apresentar a sequência completa? As duas operações podem aumentar o tamanho de um resultado, mas não produzem necessariamente a mesma ordem. A função repeat do NumPy trata da repetição dos elementos, de acordo com uma quantidade e, quando indicado, um eixo.

A Academia Master Trader apresenta esta explicação em português para leitores de São Tomé e Príncipe. Os números são exemplos de organização de dados. Não representam cotações, sinais de negociação nem resultados financeiros. O objetivo é compreender como a repetição altera uma sequência ou uma matriz sem acrescentar novas observações à sua origem.

Repetir cada valor de uma sequência

Considere o vetor [2,5,8]. A expressão np.repeat([2,5,8],2) produz [2,2,5,5,8,8]. Cada elemento da entrada aparece duas vezes consecutivas na saída. Primeiro surgem as duas ocorrências do número dois, depois as duas do cinco e, por fim, as duas do oito.

Este resultado não é [2,5,8,2,5,8]. Essa segunda sequência corresponde à repetição do bloco completo, que é uma ideia diferente. A distinção está na ordem dos elementos. Contar seis posições em ambas as saídas não permite concluir que as duas organizações sejam equivalentes.

Figura própria: repeat transforma a sequência dois, cinco, oito em pares consecutivos de cada valor.

O segundo argumento indica o número de ocorrências de cada elemento no resultado. No exemplo, o valor dois não significa duas cópias adicionais além da ocorrência original. Significa que cada elemento aparece duas vezes ao todo. Esta leitura evita uma contagem incorreta do tamanho da saída.

Quantidades diferentes por elemento

Também é possível fornecer uma sequência de quantidades. Com a entrada [2,5,8], a expressão np.repeat([2,5,8],[1,2,3]) produz [2,5,5,8,8,8]. O primeiro elemento aparece uma vez, o segundo duas vezes e o terceiro três vezes. A correspondência entre as posições da entrada e as quantidades é parte essencial da operação.

Neste caso, a saída contém seis elementos porque um mais dois mais três é igual a seis. O total não vem de uma multiplicação uniforme pela mesma quantidade. Antes de ler o resultado, vale a pena escrever a quantidade associada a cada posição. Essa pequena descrição torna a ordem final mais clara.

A escolha das quantidades deve ser compatível com o eixo a repetir. Uma lista de números não passa a descrever livremente qualquer dimensão da matriz. É necessário relacioná-la com as posições do eixo escolhido, em vez de associá-la apenas aos valores que se veem na impressão do array.

Sem eixo, a saída é unidimensional

Imagine uma matriz com as linhas [1,2] e [3,4]. Se x guardar essa matriz, np.repeat(x,2) devolve [1,1,2,2,3,3,4,4]. Sem indicação de axis, a função utiliza a entrada achatada e apresenta uma saída unidimensional. As duas linhas da entrada deixam, portanto, de aparecer como duas linhas no resultado.

Os valores continuam numa ordem definida, mas a forma mudou. A matriz inicial tem forma (2,2), enquanto a saída deste exemplo tem forma (8,). A contagem dos elementos e a descrição dos eixos devem ser acompanhadas em separado. O facto de a entrada ter duas dimensões não obriga a saída sem eixo a manter essa organização.

Escolher o eixo numa matriz

Na mesma matriz, np.repeat(x,2,axis=0) repete as posições ao longo do primeiro eixo. O resultado tem quatro linhas: [1,2], [1,2], [3,4] e [3,4]. A forma passa a ser (4,2). Cada linha aparece duas vezes consecutivas, e o número de colunas permanece igual.

Já np.repeat(x,2,axis=1) produz duas linhas: [1,1,2,2] e [3,3,4,4]. A forma é (2,4). Agora, a repetição ocorre ao longo das colunas. O número de linhas mantém-se. Ambos os resultados possuem oito elementos, mas os eixos aumentados e a disposição visível são diferentes.

Uma forma prática de ler estas expressões consiste em anotar primeiro a forma original, depois o eixo e finalmente as quantidades de repetição. Só então se escreve a forma esperada. Esta ordem separa a intenção da aparência do resultado e ajuda a explicar cada posição sem depender da memória visual.

Repetição não é informação nova

Duplicar um valor não equivale a recolher outra observação. Se o número cinco vier de uma medição, repeti-lo duas vezes não cria automaticamente uma segunda medição independente. O programa passou a guardar mais ocorrências, mas a origem do valor continua a ser a mesma. A interpretação depende do uso que será dado à estrutura.

A função repeat descreve uma transformação do array. Ela não decide se a repetição é adequada para uma média, uma tabela ou outro cálculo posterior. Essa decisão pertence ao contexto dos dados. Documentar por que motivo cada elemento foi repetido é tão importante quanto conhecer a forma da saída.

Continue a aprender com a Academia Master Trader em academiamastertrader.com.br. Aprenda dá acesso aos conteúdos educativos. Compare a ordem dos elementos, identifique o eixo e confirme a forma final. Estas três leituras distinguem a repetição de valores de uma alteração real na informação de origem.

NumPy ones erzeugt ein Array voller Einsen und behält die vorgegebene Form bei

Eine Eins kann eine Zahl in einem Vektor, ein Eintrag in einer Matrix oder ein Platzhalter in einer vorbereiteten Struktur sein. Die Funktion ones von NumPy legt ein neues Array an und füllt jede seiner Positionen mit einer Eins. Welche Bedeutung diese Einträge später erhalten, entscheidet das Programm, nicht der Funktionsname.

Academia Master Trader erklärt diesen Zusammenhang auf Deutsch für Leserinnen und Leser in Liechtenstein. Die Beispiele behandeln ausschließlich die Organisation numerischer Arrays. Sie bilden keine Kurse, Handelssignale oder finanziellen Ergebnisse ab. Im Mittelpunkt stehen die Form, der Datentyp und der Unterschied zwischen einer vollständig gefüllten Matrix und einer Einheitsmatrix.

Zwei Zeilen mit jeweils drei Einsen

Mit np.ones((2,3),dtype=int) entsteht ein Array mit zwei Zeilen und drei Spalten. Beide Zeilen enthalten [1,1,1]. Die Form lautet (2,3), und die Gesamtzahl der Elemente beträgt sechs. Der erste Wert des Formtupels beschreibt die Zeilenzahl, der zweite die Spaltenzahl.

Jede Position erhält denselben Wert. Dennoch bleiben die Positionen voneinander getrennt. Der Eintrag an den Koordinaten (0,0) ist eine andere Position als der Eintrag an (1,2). Gleiche Werte heben die räumliche Anordnung der Matrix nicht auf. Diese Trennung zwischen Position und Inhalt hilft beim Lesen größerer Arrays.

Eigene Abbildung: ones erzeugt zwei Zeilen und drei Spalten mit insgesamt sechs Einsen.

Die Funktion sucht dabei keine vorhandenen Einsen. Sie zählt auch nicht, wie häufig ein bestimmter Wert in einer Datenreihe vorkommt. Sie erzeugt eine neue Struktur anhand der angegebenen Form. Die sechs Einsen stammen aus der Initialisierung, nicht aus sechs unabhängigen Beobachtungen einer äußeren Datenquelle.

Eine Dimension ist keine Matrixzeile

Der Ausdruck np.ones(3,dtype=int) liefert den Vektor [1,1,1]. Seine Form lautet (3,). Er besitzt genau eine Achse mit drei Elementen. Das Komma in dieser Schreibweise gehört zur Darstellung eines Tupels mit einem einzigen Eintrag und kennzeichnet keine zweite Dimension.

Dagegen erzeugt np.ones((1,3),dtype=int) eine zweidimensionale Struktur mit einer Zeile und drei Spalten. Ihre Form lautet (1,3). Der Ausdruck np.ones((3,1),dtype=int) erzeugt drei Zeilen mit jeweils einer Spalte. Alle drei Varianten enthalten drei Einsen, besitzen aber nicht dieselbe Form. Die Anzahl der Werte allein reicht deshalb zur Beschreibung nicht aus.

Wer ein Array weiterverarbeitet, sollte seine Achsen ausdrücklich benennen. Eine Anweisung, die entlang einer bestimmten Achse arbeitet, erhält damit eine klare Grundlage. Die sichtbare Wiederholung der Zahl Eins ist keine zuverlässige Auskunft darüber, ob ein Vektor, eine Zeilenmatrix oder eine Spaltenmatrix vorliegt.

Den Datentyp bewusst wählen

Ohne ausdrückliche Angabe von dtype verwendet ones standardmäßig den Datentyp float64. Bei np.ones((2,3)) werden die Werte deshalb als Gleitkommazahlen angelegt. In der üblichen Darstellung erscheint entsprechend 1. statt 1. Die Positionen und die Form bleiben gegenüber dem ganzzahligen Beispiel unverändert.

Mit dtype=int werden ganzzahlige Einträge verlangt. Diese Wahl betrifft die Darstellung und Verarbeitung der Werte im Array. Sie ändert nicht die Anzahl der Zeilen oder Spalten. Es lohnt sich daher, zwei getrennte Fragen zu beantworten: Welche Form wird benötigt, und welcher Datentyp passt zur nächsten Rechenoperation?

Aus dem Funktionsnamen sollte man keinen Datentyp ableiten. Die Bezeichnung ones beschreibt die einzutragenden Werte, nicht automatisch deren numerische Darstellung. Gerade beim Vergleich von Ausgaben helfen die Eigenschaften shape und dtype, Form und Typ getrennt zu lesen, statt nur auf das Aussehen der Zahlen zu achten.

Voller Einsen bedeutet nicht Einheitsmatrix

Eine quadratische Matrix voller Einsen ist keine Einheitsmatrix. Bei np.ones((3,3),dtype=int) steht an allen neun Positionen eine Eins. Eine Einheitsmatrix derselben Größe hat dagegen Einsen auf der Hauptdiagonale und Nullen an den übrigen Positionen. Die beiden Strukturen erfüllen unterschiedliche rechnerische Aufgaben.

Dieser Unterschied besteht auch dann, wenn beide Matrizen dieselbe Form besitzen. Formgleichheit bedeutet nicht Wertgleichheit. Für eine passende Auswahl müssen deshalb sowohl die Abmessungen als auch die Regel für die Einträge betrachtet werden. Der Name identity bezeichnet bei NumPy eine andere Konstruktion als ones.

Speicheranordnung und Bedeutung auseinanderhalten

Das Argument order beschreibt bei mehrdimensionalen Arrays die Anordnung im Speicher. Unterstützt werden die Optionen C und F; C ist die Voreinstellung. Diese Wahl ersetzt nicht das Formtupel und macht aus einer Matrix voller Einsen keine Diagonalmatrix. Die sichtbare Zuordnung von Zeilen, Spalten und Werten bleibt durch die Form und die Initialisierung bestimmt.

Eine vorbereitete Matrix kann beispielsweise als Ausgangspunkt für eine spätere Berechnung dienen. Ihre Einträge sind dann gesetzte Anfangswerte. Daraus folgt noch keine Aussage über gemessene Größen. Erst die weitere Verarbeitung und die dokumentierte Herkunft erklären, wofür die Zahlen im jeweiligen Programm stehen. Die Funktion allein liefert diese fachliche Bedeutung nicht mit.

Notieren Sie vor dem Anlegen die gewünschten Achsenlängen und den benötigten Datentyp. Vergleichen Sie danach die Form des Ergebnisses mit dieser Beschreibung. Im Hauptbeispiel ergeben zwei Zeilen mal drei Spalten sechs Positionen. Alle sechs sind mit Eins gefüllt, ohne dass dadurch ihre Koordinaten verschwinden.

Vertiefen Sie Ihr Wissen mit Academia Master Trader auf academiamastertrader.com.br. Aprenda führt zu den Lerninhalten. Beginnen Sie mit der Form, unterscheiden Sie die Datentypen und klären Sie anschließend die Bedeutung der Einträge. So bleibt eine bewusst initialisierte Struktur von einer bereits erhobenen Datenreihe unterscheidbar.

NumPy zeros crée un tableau rempli de zéros sans réduire le nombre de ses positions

Un tableau rempli de zéros n'est pas un tableau sans éléments. Il possède une forme, un nombre de positions et un type de données. NumPy zeros permet de construire cette structure directement. Chaque position reçoit zéro dès la création. La première question à poser concerne donc les dimensions souhaitées, et non une liste de valeurs à recopier.

Academia Master Trader propose cette explication en français pour les lecteurs à Monaco. Les exemples décrivent uniquement la structure de tableaux numériques. Ils ne représentent ni des prix de marché, ni des signaux, ni des résultats financiers. Le but est de séparer clairement une valeur numérique, une position et une dimension.

Construire deux lignes et trois colonnes

L'expression np.zeros((2,3),dtype=int) produit un tableau dont les deux lignes sont [0,0,0] et [0,0,0]. Sa forme est (2,3). Il contient six éléments, tous égaux à zéro. Le premier nombre indique les lignes et le deuxième les colonnes. Le choix dtype=int précise un type entier pour cet exemple.

Les positions existent même si leurs valeurs sont identiques. L'élément de coordonnées (0,0) et celui de coordonnées (1,2) sont deux éléments distincts du tableau. Ils contiennent simplement la même valeur. La répétition des zéros n'efface donc pas l'organisation en lignes et en colonnes.

Schéma original : zeros crée deux lignes et trois colonnes contenant six valeurs nulles.

La fonction ne cherche pas les zéros dans une série existante. Elle ne calcule pas non plus combien d'observations valent zéro. Elle crée un nouveau tableau selon la forme fournie. Les six zéros de cet exemple viennent de la règle de construction, pas d'une collecte de six observations indépendantes.

Une dimension n'est pas une ligne de matrice

Avec np.zeros(3,dtype=int), le résultat est [0,0,0] et sa forme est (3,). Il possède un seul axe de longueur trois. Cette structure diffère de celle produite par np.zeros((1,3),dtype=int), qui possède deux axes et représente une ligne avec trois colonnes.

De même, np.zeros((3,1),dtype=int) construit trois lignes d'une seule colonne. Sa forme est (3,1). Ces trois exemples contiennent chacun trois valeurs, mais ils ne décrivent pas la même organisation. Le nombre total d'éléments ne suffit donc pas à connaître les dimensions du tableau.

Écrivez la forme avant de lire les valeurs. Une suite de trois zéros peut paraître semblable dans plusieurs affichages, alors que les axes diffèrent. Cette distinction devient utile lorsqu'une opération suivante attend explicitement une matrice plutôt qu'un tableau à une dimension.

Le type par défaut est distinct de la forme

La documentation indique numpy.float64 comme type par défaut. Ainsi, np.zeros((2,3)) crée par défaut un tableau numérique en virgule flottante. Les valeurs peuvent être affichées sous la forme 0. au lieu de 0. Le point ne signifie pas qu'une dimension supplémentaire a été ajoutée.

L'argument dtype permet de choisir explicitement un type. Dans notre exemple principal, dtype=int produit des valeurs entières. Le tableau garde deux lignes et trois colonnes. Le type règle la représentation des éléments; la forme règle leur organisation. Modifier l'un ne redéfinit pas automatiquement l'autre.

Ce choix mérite d'être fait en fonction des calculs prévus. Une initialisation à zéro ne dit pas, à elle seule, quel type convient à toutes les opérations ultérieures. Notez le type voulu au même moment que la forme pour rendre la construction lisible dans le programme.

Zéro ne veut pas dire donnée absente

La valeur zéro possède ici un sens numérique précis: c'est la valeur placée dans chaque élément à la création. La fonction ne lui attribue pas automatiquement le sens de donnée manquante, de résultat inconnu ou d'observation non reçue. Si votre programme lui donne une signification particulière, cette convention doit être définie séparément.

Par exemple, un tableau de six zéros peut être une structure de départ avant d'autres calculs. Cela ne prouve pas que six mesures ont été réalisées et qu'elles ont toutes donné zéro. Distinguez les valeurs créées pour organiser un calcul des valeurs obtenues à partir d'une source de données.

Cette distinction concerne l'interprétation, pas la forme. Le tableau reste composé de six éléments dans les deux cas. C'est la provenance des valeurs et la règle du programme qui permettent de comprendre ce que ces éléments représentent.

Lire les arguments dans le bon ordre

La fonction accepte notamment shape, dtype et order. L'argument order concerne l'organisation en mémoire des tableaux multidimensionnels, avec les options C et Fortran. Il ne remplace pas les dimensions demandées et ne transforme pas les zéros en une autre valeur. La structure visible reste déterminée par la forme.

Avant la création, notez le nombre d'axes et la longueur de chacun. Après la création, comparez la forme obtenue avec cette description. Pour l'exemple principal, deux lignes multipliées par trois colonnes donnent six positions. Toutes ont été initialisées à zéro, sans qu'aucune ligne ait disparu.

Poursuivez votre apprentissage avec Academia Master Trader sur academiamastertrader.com.br. Aprenda donne accès au contenu pédagogique. Commencez par la forme, choisissez le type et précisez ensuite le rôle des valeurs créées. Ces étapes distinguent une structure initialisée d'une série de données déjà observées.

NumPy full creates an array with a chosen shape and a value supplied in advance

An array does not always begin with a collection of different observations. Sometimes the task is to create a structure of a known size and fill its positions with a chosen value. NumPy full does that directly. Its first argument describes the shape, and its second supplies the value used to fill the new array.

Academia Master Trader presents this lesson in English for readers in Malta. The numbers are invented examples of array structure. They are not market prices, trading signals or financial results. The aim is to make the relationship between dimensions, stored values and data type clear before the array enters another calculation.

Shape and fill value have separate jobs

Consider np.full((2,3),7). The shape is (2,3), so the output has two rows and three columns. Both rows contain [7,7,7]. There are six positions altogether, and every position contains the supplied value seven. The number seven does not describe the number of rows or columns.

Conversely, the numbers two and three do not become the stored values. They define the structure that receives those values. Keeping these roles separate makes the call easier to read: first describe the container, then state what should occupy it. A chosen fill value does not add an extra axis.

Original diagram: full creates two rows and three columns, with seven in every position.

The result is a new array. It is not a request to change an existing array in place, and it does not calculate a running total from earlier observations. All six entries in this example come from the construction rule. Their repetition says nothing about how many independent observations have been collected.

One dimension is different from two

The shape argument can also be an integer. With np.full(4,7), the result is the one-dimensional sequence [7,7,7,7], with shape (4,). There is one axis of length four. This differs from np.full((1,4),7), which creates a two-dimensional array containing one row and four columns.

Those two outputs contain the same number of elements, but their shapes are different. A later operation that expects rows and columns may therefore treat them differently. Count the axes as well as the elements. Four stored numbers do not by themselves tell you whether the array has one dimension or two.

A shape of (4,1) describes another arrangement: four rows and one column. Each row contains a single seven. The shape is not interchangeable with (1,4), even though both describe four positions. Reading the dimensions in their stated order is part of understanding the construction.

The fill value also informs the default type

When dtype is not supplied, the documentation defines the default type through np.array(fill_value).dtype. The fill value therefore matters for more than the numbers displayed. An integer fill value and a value written in floating-point form can lead to different array data types.

For a clear explicit choice, np.full((2,3),7,dtype=float) creates the same two-by-three arrangement with floating-point values. They may be displayed as 7. rather than 7. That display does not change the shape or add information about measurement accuracy. It reflects the numerical representation selected for the array.

Choose the type according to the operations that will follow. Do not assume that changing dtype changes the number of rows, and do not assume that the appearance of a decimal point means the values came from a measured series. Shape, value and type answer separate questions.

A fill value can contain more than one element

The documented fill_value parameter accepts a scalar or an array-like value. The official example np.full((2,2),[1,2]) produces the rows [1,2] and [1,2]. The two-element input is used across the rows in that example. The output still has the shape given by the first argument.

This does not mean that an arbitrary sequence can fill every requested shape. The relationship between the supplied values and the target shape must be compatible. For an introductory example, use a scalar when every position should contain the same number. Use a small explicit pattern only after checking how it fits the requested dimensions.

Memory order is not a different visible pattern

The order argument concerns how multidimensional data is stored in memory. The documentation offers C or Fortran order. This is separate from the chosen values and the visible arrangement of rows and columns. Changing the storage order is not a way to replace seven with another number or exchange the two dimensions.

Before constructing the array, write down the expected shape and one expected row. Afterwards, compare those with the output. For the main example, the description is two rows, three columns and seven in every position. That short statement keeps the construction clear without treating repeated entries as separate source data.

Continue learning with Academia Master Trader at academiamastertrader.com.br. Aprenda gives access to educational material. Start with the required dimensions, choose the fill value and then decide whether the type needs to be explicit. These separate steps make a newly created array easier to understand and reuse.

NumPy identity costruisce una matrice quadrata con uno sulla diagonale principale

Una matrice identità ha una struttura semplice: gli elementi della diagonale principale valgono uno e tutti gli altri valgono zero. NumPy identity permette di costruire questo array indicando un solo numero per le dimensioni. Quel numero stabilisce sia quante righe sia quante colonne contiene il risultato.

Academia Master Trader propone questa spiegazione in italiano per i lettori di San Marino. I numeri degli esempi descrivono forme e posizioni di un array. Non rappresentano prezzi di mercato, segnali operativi o risultati finanziari. La lezione riguarda la costruzione di una matrice e la lettura corretta dei suoi parametri.

Un numero per due dimensioni

L'espressione np.identity(3,dtype=int) crea una matrice con le righe [1,0,0], [0,1,0] e [0,0,1]. La sua forma è (3,3). Il parametro n vale tre, quindi ci sono tre righe e tre colonne. Il risultato è un array bidimensionale, non un vettore con tre elementi.

Gli elementi uguali a uno occupano le posizioni (0,0), (1,1) e (2,2). Su questa diagonale l'indice di riga coincide con quello di colonna. Gli altri sei elementi sono zero. Le posizioni si contano da zero: la prima riga ha indice zero e la terza ha indice due.

Schema originale: identity crea una matrice quadrata tre per tre con uno sulla diagonale principale.

È utile distinguere il valore di n dal numero totale di elementi. Con n=3 la matrice contiene nove posizioni, perché ogni riga contiene tre elementi e ci sono tre righe. Solo tre posizioni appartengono alla diagonale principale. Il parametro non indica quindi la lunghezza di una sequenza piatta già pronta.

La diagonale nasce dalla costruzione

La funzione non riceve una matrice da cui estrarre dei valori. Non cerca una diagonale in dati esistenti e non dispone lungo la diagonale una sequenza scelta dall'utente. Crea direttamente i valori uno e zero secondo la struttura richiesta. Questa distinzione aiuta a leggere il codice senza confondere creazione ed estrazione.

Per esempio, np.identity(2,dtype=int) produce le righe [1,0] e [0,1]. Cambia la dimensione, ma non la regola. Con np.identity(4,dtype=int) si ottengono invece quattro righe e quattro colonne: [1,0,0,0], [0,1,0,0], [0,0,1,0] e [0,0,0,1]. Ogni riga contiene un solo uno.

In questi esempi, la somma degli elementi di ogni riga è uno e quella degli elementi di ogni colonna è uno. Questa osservazione deriva dai valori costruiti. Non significa che identity sommi dati ricevuti in ingresso. La funzione restituisce la matrice; un'eventuale somma è un'operazione successiva e distinta.

Il tipo dei valori è un'altra scelta

La documentazione indica float come tipo predefinito. Perciò np.identity(3) viene mostrato con valori come 1. e 0. L'argomento dtype=int usato nello schema rende esplicita la scelta di valori interi. La struttura delle posizioni rimane la stessa nei due casi.

Il tipo non cambia il numero di righe o di colonne. Una matrice intera di forma (3,3) e una matrice in virgola mobile della stessa forma hanno entrambe nove posizioni. Prima di proseguire con altre operazioni, conviene tenere separate due domande: quale forma serve e quale tipo di elementi deve contenere.

La notazione con il punto negli esempi della documentazione non aggiunge una dimensione. È una rappresentazione del valore numerico. Allo stesso modo, scegliere dtype non trasforma automaticamente una matrice quadrata in una rettangolare. Il parametro n continua a determinare entrambi i lati.

Quando serve una costruzione diversa

La firma di identity prevede n, dtype e il parametro opzionale like. Non prevede un parametro M per scegliere separatamente il numero di colonne e non prevede k per spostare la diagonale. Per queste due possibilità, la documentazione di NumPy eye descrive una costruzione più flessibile.

Una matrice con tre righe e quattro colonne non è dunque il risultato richiesto a identity(3). Il risultato di quell'espressione è quadrato. Anche una diagonale spostata sopra la principale descrive un'altra struttura. Chiarire questa differenza prima di scrivere la chiamata evita di attribuire alla funzione argomenti che non possiede.

Leggere insieme forma, indici e valori

Prima della costruzione, scrivete n e la forma attesa (n,n). Dopo la costruzione, osservate una riga iniziale, una centrale e l'ultima. Nella matrice di ordine tre, l'uno passa dalla prima alla seconda e poi alla terza colonna. Questo andamento descrive le posizioni della diagonale, non uno spostamento eseguito su valori già presenti.

Confrontate poi due posizioni fuori diagonale: entrambe devono contenere zero, anche se si trovano in righe diverse. La regola è uniforme su tutta la matrice. Una descrizione completa comprende quindi dimensioni, diagonale principale e tipo, senza confondere il valore uno con l'indice della posizione che lo ospita.

Continuate a studiare con Academia Master Trader su academiamastertrader.com.br. Il collegamento Aprenda porta ai contenuti educativi. Partite dalla forma, individuate la diagonale e leggete infine i valori. Separare questi passaggi rende più chiara la costruzione dell'array prima di utilizzarlo in altri calcoli.