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 argsort returns the original positions that arrange values in sorted order

Sorting values and finding their sorting positions answer different questions. NumPy sort returns arranged values, while argsort returns indices describing which original positions to read and in what order. Academia Master Trader explains argsort in English for readers in Germany. The examples use small constructed arrays and zero based indices. The aim is to preserve the relationship between an entry and its original position while explaining a numerical ordering.

Read the returned numbers as positions

After import numpy as np, define x = np.array([8,2,6,4]). The call idx = np.argsort(x) returns [1,3,2,0]. These numbers are indices, not the sorted values. The smallest entry two is at original index one. Four is at index three, six at index two, and eight at index zero.

Using those indices, x[idx] returns [2,4,6,8]. Read the instruction as: take x at index one, then three, then two, then zero. The output from argsort gives the order in which to visit the original positions. It does not give each original entry's rank at that same position.

NumPy argsort

Follow the diagram from values to positions

The figure shows the original values, the argsort indices and the values retrieved through those indices. The middle row begins with one because the first sorted value comes from original position one. Its final zero points back to the original eight. Keeping all rows labelled prevents the index sequence from being mistaken for another set of measurements.

The call does not change x. Saving the indices separately keeps the original sequence available and gives an explicit arrangement to apply where appropriate. That is useful when explaining how sorted values relate to the source, rather than displaying the sorted numbers without their positional history.

Keep associated labels aligned

Suppose labels = np.array(['A','B','C','D']), where each label belongs to the entry at the same original position in x. The expression labels[idx] returns ['B','D','C','A']. Applying the same index order to both arrays keeps each label with its corresponding value.

This only works when the original arrays really share that positional relationship. A label array from another sequence does not become correctly matched merely because it has four entries. Establish the association first, then apply the indices. Sorting values alone and leaving labels in their original order would describe different pairings.

For matrices, indices belong to the selected axis

Define a = np.array([[8,2,6],[3,9,1]]). The call np.argsort(a,axis=1) returns [[1,2,0],[2,0,1]]. Each row contains column indices for sorting that row. The first row should read columns one, two and zero; the second should read columns two, zero and one.

Apply the indices with np.take_along_axis(a,np.argsort(a,axis=1),axis=1) to obtain [[2,6,8],[1,3,9]]. The function name is written exactly here because the operation applies indices along a named axis. Ordinary one dimensional indexing syntax should not be assumed to mean the same thing for a matrix.

Make ties and flattening explicit

For repeated values, np.argsort([5,2,5],kind='stable') returns [1,0,2]. A stable sort preserves the original relative order of entries comparing equal. The two fives therefore appear through original positions zero and two in that order. Without a stable ordering choice, that tie order is not guaranteed.

Choosing axis=None makes argsort work on the flattened input. Those indices then refer to flattened positions, not directly to row and column pairs. Name the intended axis before interpreting the returned integers.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the original values, index convention, sorting axis and any stability requirement. Then retrieve the values with the returned indices. Those checks distinguish sorting positions from values, ranks and any claim about future observations.

NumPy sort orders values along a selected axis and returns a separate sorted copy

A sequence can be arranged by value without changing which numbers it contains. Sorting makes that arrangement explicit, but it can also remove the original positional story if the input order mattered. Academia Master Trader explains NumPy sort in English for readers in Austria, using small constructed arrays. The examples distinguish numerical order, matrix axes and the difference between a sorted copy and a change to the original array.

Begin with an ordinary numerical sequence

After import numpy as np, define x = np.array([8,2,6,2,5]). The call np.sort(x) returns [2,2,5,6,8]. The smallest values appear first and the largest last. Both copies of two remain in the result. Sorting does not remove repeated values, calculate an average or invent new entries between the existing ones.

The input and output each contain five entries. What changes is their arrangement. If the original positions represented a time sequence, the sorted result no longer represents that same chronological order. The numbers are still present, but their neighbours and positions may have changed. A label should therefore distinguish a sorted view from the original sequence.

NumPy sort

Keep the source and the returned copy separate

The figure places x in gold and its sorted copy in grey. Reading both rows confirms that eight moves toward the end while the two repeated values move together at the beginning. Those visual changes concern the returned result. Calling y = np.sort(x) leaves x unchanged and stores the sorted copy in y.

The array method x.sort() has different behaviour: it sorts x in place. Choose deliberately between retaining the original array and changing it. If you need to compare the original positions with sorted positions later, preserve the original information instead of assuming the sorted values can reconstruct every earlier arrangement.

Sort rows independently with the last axis

Define a = np.array([[8,2,6],[3,9,1]]), with shape (2,3). The call np.sort(a,axis=1) returns [[2,6,8],[1,3,9]]. Each row is sorted separately. Values do not move from the first row into the second. The default axis is the last axis, so np.sort(a) gives the same result for this matrix.

The output retains shape (2,3), but positions within each row have changed. This matters if another array stores related information at matching positions. Sorting only the numerical values does not automatically carry that other information along. NumPy provides argsort for obtaining sorting indices; the simple sort examples here return values rather than those indices.

Compare column sorting with flattening

The call np.sort(a,axis=0) returns [[3,2,1],[8,9,6]]. Each column is sorted from its smaller entry to its larger entry. The first column compares eight and three, the second compares two and nine, and the third compares six and one. The result is not a list of globally smallest values across the first row.

The call np.sort(a,axis=None) instead returns [1,2,3,6,8,9]. It flattens the matrix before sorting all six values together. The result is one dimensional, unlike the two axis specific outputs. Naming the axis or explicitly choosing None keeps those different operations visible.

Treat equal values and numerical types carefully

When stable ordering is required, kind='stable' requests a stable sort. Stability means that entries comparing equal retain their relative order. In a plain numerical output containing two identical values, that distinction may not be visible from the numbers alone. It still matters when explaining sorting methods or working with associated records.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record whether the operation returns a copy or changes the input, which axis is sorted and whether the output preserves the intended relationships. These checks keep a numerical arrangement distinct from chronology, deduplication and any claim about future values.

NumPy where chooses between two sources at each position using an explicit condition

Choosing a value by a condition is different from removing every position that fails it. With three arguments, NumPy where builds an output by selecting from one source where the condition is true and another where it is false. Academia Master Trader explains that operation in English for readers in Switzerland. The small arrays below are constructed numerical examples. Their conditions describe a processing rule, not a forecast or evidence of investment performance.

State the condition and both choices

After import numpy as np, define a = np.array([2,7,4,9]). The comparison a > 5 gives [False,True,False,True]. The call np.where(a > 5,a,0) returns [0,7,0,9]. At positions where the comparison is true, the output takes the corresponding entry from a. Where it is false, the output takes zero.

The argument order is condition, choice for true, choice for false. Reversing the last two arguments changes the rule. For example, np.where(a > 5,0,a) returns [2,0,4,0]. The comparison did not change, but the sources attached to its two possible outcomes did.

NumPy where

Read one position at a time

The figure shows the original entries, the comparison results and the selected output. Begin with two: it is not greater than five, so the result is the false choice zero. Seven is greater than five, so the next output is seven. Applying the same rule to four and nine gives zero and nine.

All four positions remain in this example. The zeros are chosen replacement values, not original measurements of zero. Keeping the original a available makes it possible to explain what those positions contained before selection. The output alone does not preserve that information when several original values share the same false choice.

Compare selection with filtering

The expression a[a > 5] returns [7,9], which contains only the entries whose comparison is true. That is a filtered result with two entries. By contrast, np.where(a > 5,a,0) returns four entries because every original position receives one of the two choices.

Choose between these operations from the structure you need. A position preserving result can remain aligned with another four entry array. A filtered result has a different length. Neither result is automatically more informative; they answer different questions, and their labels should identify which operation was used.

Use two arrays as the value sources

Define b = np.array([20,70,40,90]). The call np.where(a > 5,a,b) returns [20,7,40,9]. The false positions now take twenty and forty from b instead of a shared zero. The true positions still take seven and nine from a. Selection compares no values from b with five in this expression: the condition was defined entirely from a.

This separation lets a condition come from one calculation while the chosen values come from other arrays. Explain that relationship explicitly. A reader should be able to identify the condition, the true source and the false source without inferring them from the final numbers.

Check shapes and distinguish the one argument form

The condition and both sources must be broadcastable to a common shape. The scalar zero in the first example supplies the same false choice at every position. For a matrix example, np.where([[True,False],[False,True]],[[2,3],[4,5]],0) returns [[2,0],[0,5]], preserving the common two by two structure.

Calling where with only a condition has a different role: it returns index arrays through the nonzero operation rather than choosing between two value sources. NumPy recommends using nonzero directly for that purpose. Keep that form separate from the three argument examples explained here.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the condition, both sources and their common shape. Then follow one true and one false position manually. Those checks keep value selection distinct from filtering and from a claim that the selected values predict anything.

NumPy clip limits array values to chosen boundaries without removing their positions

Limiting a number and removing it from a sequence are different operations. A clipped array keeps its positions while values beyond the chosen boundaries are replaced by boundary values. Academia Master Trader explains NumPy clip in English for readers in Belgium. The examples use small constructed arrays so the replacements can be followed directly. The boundaries are explicit processing choices, not facts discovered by the function or claims about future market behaviour.

Begin with one lower and one upper bound

After import numpy as np, define x = np.array([-3,2,5,9,14]). The call np.clip(x,0,10) returns [0,2,5,9,10]. Minus three is below the lower bound zero, so it becomes zero. Fourteen is above the upper bound ten, so it becomes ten. Two, five and nine already lie inside the interval and remain unchanged.

Five input positions produce five output positions in this example. The function does not drop the first or last entry. Nor does it sort the entries or redistribute the values evenly between zero and ten. It applies the boundary rule to each value at its existing position.

NumPy clip

Read changed and unchanged entries separately

The figure places the original entries in gold and the clipped output in grey. Compare the two rows position by position. Only the first and fifth values differ. The output zero is a boundary replacement for minus three, not an original observation of zero. Likewise, the final ten replaces fourteen; it does not report that fourteen was originally ten.

This distinction matters whenever an explanation presents processed values alongside source values. Keep the input available if the original magnitude is still needed. Several different inputs can map to the same boundary. For example, both fourteen and twenty would become ten under the same upper limit, so the clipped result alone does not identify which original value produced it.

Apply only the boundary you need

The call np.clip(x,0,None) returns [0,2,5,9,14]. The lower limit applies, while None leaves the upper side unrestricted. By contrast, np.clip(x,None,10) returns [-3,2,5,9,10]. The upper limit applies and the negative first entry remains unchanged.

Choose the boundary from the meaning of the processing task. The function can apply a numerical rule, but it cannot decide whether that rule is suitable for the data. Write the limit and the reason for using it in the surrounding explanation, rather than presenting a clipped output as though no transformation occurred.

Bounds can also vary by position

For the same x, np.clip(x,[0,3,0,10,0],12) returns [0,3,5,10,12]. The lower limits now vary across the five positions, while the upper limit remains twelve. The second input two becomes three because its own lower limit is three. The fourth input nine becomes ten because its own lower limit is ten.

NumPy broadcasts the bounds against the input. In this example, the lower bound array has the same length as x and the single upper bound applies to every position. A more complex shape needs an explicit explanation of which limit belongs to which entries. The compact syntax does not make that association optional.

Check the boundary order before relying on the result

NumPy does not check that the lower boundary is smaller than the upper boundary. With reversed scalar limits, np.clip(x,10,0) returns [0,0,0,0,0]. This is defined behaviour, not an instruction to treat zero as a sensible result for every application. Confirm the intended order of the bounds before interpreting the output.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the original values, lower and upper boundaries, any position specific limits and the resulting shape. Then identify which entries changed. That keeps clipping distinct from filtering, sorting and recovering the original measurements.

NumPy cumprod preserves intermediate products while following a chosen accumulation axis

Multiplication across a sequence can be recorded as a single final product or as a series of running products. The second view shows how each new factor changes the accumulated result. Academia Master Trader explains NumPy cumprod in English for readers in Luxembourg, using small constructed arrays. These examples describe numerical operations, not reported investment outcomes. The focus is the distinction between a factor and the product reached after including that factor.

Follow each multiplication in order

After import numpy as np, define x = np.array([2,3,-1,4]). The call np.cumprod(x) returns [2,6,-6,-24]. The first running product is two. Multiplying by three gives six. Multiplying that result by minus one gives minus six, and multiplying by four gives minus twenty four. Every result includes all entries from the start through its own position.

Four input factors produce four output products. The function retains the intermediate values rather than returning only minus twenty four. It also differs from a cumulative sum: six in the second position comes from two multiplied by three, not from adding them. Naming the operation matters even when a particular example happens to contain a similar number.

NumPy cumprod

Separate each factor from its running product

The figure places the original factors in gold and the accumulated products in grey. At the third position, the factor is minus one and the running product is minus six. The two rows describe different quantities. The fourth factor is four, while the fourth product is minus twenty four. A label should make that distinction explicit wherever the results are displayed.

For this signed integer sequence, the negative factor changes the sign of the running product. A zero factor would instead make that position's product zero, and subsequent multiplication by finite integer factors would keep it zero. For example, np.cumprod([2,0,3]) returns [2,0,0]. This follows ordinary multiplication; it is not a rule for replacing or ignoring zero entries.

Select separate row accumulations

Define a = np.array([[2,3,4],[5,2,1]]), with shape (2,3). The call np.cumprod(a,axis=1) returns [[2,6,24],[5,10,10]]. The running product restarts at the beginning of each row. The first row reaches twenty four. The second row begins at five and reaches ten. Multiplication by its final factor one leaves that running product unchanged.

The output keeps shape (2,3). Each position still belongs to its original row and column, but now contains a product through that point along the selected axis. Keeping the same shape does not mean keeping the original numerical meaning.

Compare columns with the flattened default

The call np.cumprod(a,axis=0) returns [[2,3,4],[10,6,4]]. Each column now accumulates downward, so its second product combines the entries from the first and second rows. This grouping differs from accumulation across each row.

Without an axis argument, np.cumprod(a) returns [2,6,24,120,240,240]. The matrix is flattened first, reading the first row followed by the second. Accumulation continues across the row boundary: the factor five multiplies the earlier product twenty four to produce one hundred twenty. The result is a one dimensional array of six products rather than a matrix of independent row products.

Choose a suitable numerical type

The optional dtype argument selects the returned type and the accumulator type. Integer multiplication can exceed the chosen type's capacity; NumPy uses modular arithmetic without raising an overflow error for these integer operations. Choose a type that suits the intended values and sequence length, rather than treating a familiar output shape as proof of suitable arithmetic.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input factors, axis or flattened order, numerical type and output shape. Follow several products manually, including any sign change or zero. That makes the calculation explainable without turning a running product into a claim about future values.

NumPy cumsum returns every running total and makes the accumulation axis explicit

A final sum answers how much a collection adds up to. A cumulative sum also retains the total reached at every earlier position. Academia Master Trader explains NumPy cumsum in English for readers in Cyprus, using a short sequence and a small matrix. The examples are constructed arithmetic, not reported market observations. The aim is to distinguish individual entries from running totals and to keep the direction of accumulation clear.

Build a running total one entry at a time

After import numpy as np, define x = np.array([3,5,-2,4]). The call np.cumsum(x) returns [3,8,6,10]. The first result is three. The second adds five to that running total, giving eight. The third adds minus two, giving six. The fourth adds four, giving ten. The negative entry reduces the running total; the function does not force the output to rise.

Each output position contains the sum of all input entries up to and including that position. Four inputs therefore produce four cumulative outputs. This differs from an adjacent difference, which compares pairs and normally shortens a one dimensional sequence. It also differs from returning only the final sum, because the intermediate totals remain available.

NumPy cumsum

Separate the contribution from the accumulated amount

The figure places the input entries in gold and their cumulative totals in grey. At the third position, the input contribution is minus two, while the accumulated amount is six. These are different quantities associated with the same position. A label should say whether it describes an entry or the running total through that entry.

The final total ten includes every contribution in the example. It is not a fifth input entry and should not be appended to the original sequence as though it were a new observation. When presenting an accumulated series, keep the original values available if readers need to explain which contribution changed the total at a particular step.

A matrix requires a direction

Define a = np.array([[3,5,2],[4,1,6]]), with shape (2,3). The call np.cumsum(a,axis=1) returns [[3,8,10],[4,5,11]]. Accumulation restarts for each row. In the first row, three becomes eight and then ten. In the second row, four becomes five and then eleven. The result keeps the matrix shape.

The call np.cumsum(a,axis=0) returns [[3,5,2],[7,6,8]]. Here each column has its own running total from the first row onward. The second row contains three plus four, five plus one, and two plus six. Changing the axis changes which entries are accumulated together, even though the input values and output shape remain the same.

The default flattens the matrix

Without an axis argument, np.cumsum(a) returns [3,8,10,14,15,21]. For this matrix, the flattened sequence reads the first row followed by the second row, and accumulation continues across the row boundary. Four is therefore added to ten, producing fourteen, rather than starting a separate row total at four.

That one dimensional result has six entries. Compare it with the two axis specific matrix results before choosing a form for an explanation. A familiar looking first total is not enough to establish that the intended grouping was used.

Choose an accumulator type that suits the values

The optional dtype argument controls the returned type and accumulator type. Integer overflow uses modular arithmetic, so large cumulative totals need a suitable integer capacity. Floating point accumulation can involve rounding, and its final value may differ slightly from a separately calculated sum that uses another summation approach. These are numerical properties, not evidence of additional input data.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the original entries, the axis or flattened order, the accumulator type and the output shape. Then follow several additions manually. Those checks make each running total explainable without confusing it with a separate contribution or a forecast.

NumPy diff measures consecutive changes along an axis rather than returning the original levels

A sequence of levels and a sequence of changes describe different things. The level tells you the value at one position. A consecutive difference tells you how much the next value differs from the current one. Academia Master Trader explains NumPy diff in English for readers in Moldova, using small arrays whose arithmetic can be followed directly. These are constructed numerical examples, not market observations or evidence of financial performance.

Start with the direction of subtraction

After import numpy as np, define x = np.array([4,9,7,13]). The call np.diff(x) returns [5,-2,6]. The first result is nine minus four. The second is seven minus nine. The third is thirteen minus seven. Each result uses the later entry minus the earlier entry, not the reverse.

Four original entries create three adjacent pairs, so the output has length three. The first difference does not supply a change before the first original entry, because no earlier entry was provided. A shorter result is therefore expected. It is not a missing piece that should automatically be filled with zero.

Keep changes distinct from levels

The output five belongs to the pair four and nine; it is not a replacement level for four. Likewise, minus two describes the move from nine to seven. If you store differences beside their source sequence, choose and explain an alignment. For example, you might associate each change with the later entry of its pair. NumPy returns an array of numbers, while your explanation supplies that interpretation.

NumPy diff

Read the diagram in two stages

The figure places the original four entries in a gold row and the three first differences underneath. Read consecutive pairs from the original row and subtract in the stated direction. Then read the final row, which contains differences between consecutive first differences. Keeping these rows separate makes the meaning of each number visible without confusing a level with a change.

The first difference can be positive, negative or zero. A positive result means the next numerical value is larger. A negative result means it is smaller. Zero means the two adjacent entries are equal. Those descriptions concern the supplied values only; they do not predict the next value or explain why a sequence changed.

A second difference repeats the operation

The call np.diff(x,n=2) returns [-7,8]. Start from the first differences [5,-2,6]. Minus two minus five gives minus seven; six minus minus two gives eight. This operation does not subtract every second original entry. It applies consecutive differencing twice.

The output now has length two. With a sequence long enough for the requested order, each additional round removes one position along the selected axis. Write down the intermediate differences when explaining a higher order result. The arithmetic is easier to inspect when the transformation remains visible.

Choose the axis explicitly for a matrix

Define a = np.array([[4,9,7],[6,8,12]]). The call np.diff(a,axis=1) returns [[5,-2],[2,4]]. Each row is treated separately, and the shape changes from (2,3) to (2,2). By contrast, np.diff(a,axis=0) returns [[2,-1,5]], subtracting the first row from the second at matching columns. Its shape is (1,3).

The default axis is the last axis, so naming it explicitly can make an explanation clearer. Also choose a suitable data type: unsigned integer subtraction can wrap around instead of representing a negative value. For ordinary signed arithmetic, use an appropriate signed type before differencing. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input, subtraction direction, order, axis and resulting shape. Those checks keep the numerical change distinct from the original values and from any interpretation you later add.

NumPy pad extends array boundaries using explicit widths and a chosen filling rule

Adding boundary entries changes an array's size and requires a rule for what those new positions contain. A zero border and a copied edge are different choices, even when they produce the same shape. Academia Master Trader explains NumPy pad in English for readers in North Macedonia. We will extend a short sequence and a small matrix, naming the widths and mode each time. Padding is an array construction rule, not a source of new measurements or evidence of financial performance.

Separate the input from its new boundary

After import numpy as np, define x = np.array([8,3,6]). The call np.pad(x,(1,2),mode='constant') returns [0,8,3,6,0,0]. The width pair means one position before the original sequence and two after it. Constant mode uses zero by default. The original entries remain together, in their original order, between the added boundaries.

The input shape is (3,), and the output shape is (6,). Its length is three original positions plus one before plus two after. Eight moves from original index zero to output index one because a new leading position was added. Three and six move by the same offset. Their relative order and numerical values remain unchanged.

Give constant padding an explicit value

The call np.pad(x,(1,2),mode='constant',constant_values=5) returns [5,8,3,6,5,5]. The widths have not changed, so the output length remains six. Only the filling rule's constant has changed from the default zero to five. The added five at the start is not an original observation, and neither are the two added fives at the end.

A padding width is a count of positions, whereas a constant value supplies their contents. Confusing those roles would produce a different array. Write the width pair and the constant separately when explaining a result. A reader should be able to identify which entries came from the input and which were introduced by the chosen boundary rule.

NumPy pad

Read the figure from the unchanged interior outward

The figure highlights the original sequence in gold inside both padded outputs. Begin with eight, three and six, then look at the single cell before them and the two cells after them. In the constant example those cells contain zeros. In the edge example they contain copies of the nearest boundary entries. The source block stays identical in both cases.

The figure's extra cells represent added array positions, not additional collected evidence. Keeping their colour separate from the original interior makes that distinction visible. Both examples have six entries, so their shapes alone cannot identify the selected mode. Inspect the boundary contents as well as the width counts before deciding what construction was used.

Use edge mode to extend the endpoint values

The call np.pad(x,(1,2),mode='edge') returns [8,8,3,6,6,6]. The leading added position copies the first entry eight. The two trailing added positions copy the last entry six. Original three remains between original eight and six. Edge mode does not repeat the whole three entry pattern, and it does not reverse the sequence.

The same widths therefore produce different outputs under constant and edge modes. Choosing a boundary rule is a modelling or processing decision, not something the input values alone determine. State it explicitly. A copied endpoint is still a copy, and a chosen constant is still a chosen constant; neither should be presented as a newly observed value outside the supplied sequence.

Specify widths for every matrix axis

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.pad(a,((1,0),(0,1)),mode='constant') returns [[0,0,0],[8,3,0],[2,9,0]], with shape (3,3). The first width pair adds one row before and none after. The second pair adds no column before and one after. All new positions contain the default constant zero.

The original eight is now at (1,0), while original nine is at (2,1). Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, a before and after width for each axis, and the selected mode. Then mark the original interior and verify the new boundary separately. Those checks explain the larger array without confusing added positions with new information.

NumPy tile repeats a whole array pattern rather than grouping copies of each entry

A repeated pattern preserves the order inside its source block. This differs from copying each entry several times before moving to the next one. Academia Master Trader explains NumPy tile in English for readers in Montenegro. We will tile a short sequence, add a row dimension and compare horizontal and vertical copies of a matrix. The expanded arrays contain repeated supplied values. They do not represent new observations, new measurements or evidence of financial performance.

Start with one complete pattern

After import numpy as np, define x = np.array([8,3,6]). The call np.tile(x,2) returns [8,3,6,8,3,6]. The original three entry sequence appears twice in the output. Its internal order remains eight, three, six in each appearance. The input shape is (3,), and the output shape is (6,).

The argument two specifies two total copies of the pattern, not two additional copies after the original. Separating the output visually into [8,3,6] followed by [8,3,6] makes that meaning explicit. Each original entry appears twice, but its appearances are separated by the other members of the pattern. This spacing is an important difference from consecutive entry repetition.

Compare tile with repeat using the same input

The call np.repeat(x,2) returns [8,8,3,3,6,6]. Its length is also six, but its grouping differs. Repeat places each value's copies next to one another. Tile copies the complete sequence before starting the next copy. Both operations expand this input, yet their outputs answer different arrangement requests.

For tile, output positions zero through two contain the first pattern and positions three through five contain the second. Eight occurs at indices zero and three. For repeat, eight occurs at zero and one instead. Track one original entry and the boundaries of its group before concluding that two similarly sized outputs are equivalent. A shared shape does not establish a shared order.

NumPy tile

Read the figure by complete blocks

The figure places the original sequence above the tiled result and the repeated entry result. Matching colours identify eight, three and six in each row. In the tiled row, read the colour sequence twice from left to right. In the repeat row, read adjacent pairs of each colour. The same original values appear in both rows, but their positions explain the difference.

All displayed numbers come from the original sequence. Repetition does not add information about a population or a time period merely by increasing the number of entries. If these values represented observations, copied appearances would still be copies. Keep the source block and the repetition rule visible whenever a larger array is used to illustrate structure.

Give a repetition count for each dimension

The call np.tile(x,(2,2)) returns [[8,3,6,8,3,6],[8,3,6,8,3,6]], with shape (2,6). The two supplied repetition counts describe a two dimensional arrangement. NumPy treats the one dimensional source as shape (1,3) for this operation, adding a leading axis. The first count creates two rows, and the second count places two source patterns along each row.

The original x remains a one dimensional array; this promotion describes how tile interprets it while constructing the result. It is not a change to x itself. Writing the promoted shape (1,3) before the final shape (2,6) helps explain why two repetition counts can produce a two dimensional result from a one dimensional input.

Distinguish horizontal and vertical matrix copies

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.tile(a,(1,2)) returns [[8,3,8,3],[2,9,2,9]], with shape (2,4). It copies the whole matrix horizontally. By contrast, np.tile(a,(2,1)) returns [[8,3],[2,9],[8,3],[2,9]], with shape (4,2), copying the whole matrix vertically.

For this two dimensional source, np.tile(a,2) is equivalent to the horizontal case because the shorter repetition specification is given a leading one. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source shape, repetition counts and complete block boundaries. Those checks keep pattern copies distinct from entry copies and make the resulting dimensions clear.

NumPy repeat duplicates entries or slices along a chosen axis rather than repeating an entire pattern

Repeating each entry is different from writing a whole sequence again. The distinction matters when an array grows and the position of each copy needs to stay clear. Academia Master Trader explains NumPy repeat in English for readers in Serbia. We will begin with a short sequence, then repeat rows and columns of a matrix. The extra entries are copies of supplied values. They are not new observations, additional measurements or evidence of financial performance.

Repeat each sequence entry consecutively

After import numpy as np, define x = np.array([8,3,6]). The call np.repeat(x,2) returns [8,8,3,3,6,6]. Each original entry appears twice before the operation moves to the next original entry. The input has shape (3,), and this output has shape (6,). A repetition count of two means two total appearances, not the original plus two additional copies.

The result is not [8,3,6,8,3,6]. That arrangement repeats the entire three entry pattern. NumPy repeat instead keeps each entry's repetitions adjacent. Follow the first value eight: its two output positions are zero and one. Three then occupies two and three, while six occupies four and five. This positional account identifies the operation more clearly than the shared output length alone.

Give different counts to different entries

The call np.repeat(x,[1,2,3]) returns [8,3,3,6,6,6]. Eight appears once, three twice and six three times. The counts describe each original position in order. The output length is the sum of those counts, so it is six in this example. The repeated groups preserve the order of the original entries.

A zero count contributes no copy of that entry. For example, np.repeat(x,[1,0,2]) returns [8,6,6]. Three is omitted because its specified count is zero, not because of its numerical size or a comparison with neighbouring values. Use compatible counts for the chosen input or axis. Naming the counts and their positions prevents a reader from interpreting them as new values to insert.

NumPy repeat

Read the figure as groups of copies

The figure shows the original sequence above the two repetition results. Matching colours connect each original entry with its output group. In the equal count result, every colour occupies two adjacent cells. In the unequal count result, the coloured groups have lengths one, two and three. Read group lengths rather than treating repeated numbers as independent measurements.

Both illustrated outputs have six entries, but they use different repetition rules. Equal output length does not establish equal content or equal grouping. The first output contains two eights; the second contains one eight. Keeping the repetition counts next to the output makes that distinction visible. The copied values retain their original numerical meaning even though their number of appearances changes.

Repeat complete rows or columns

Define a = np.array([[8,3],[2,9]]), with shape (2,2). The call np.repeat(a,2,axis=0) returns [[8,3],[8,3],[2,9],[2,9]], with shape (4,2). Axis zero selects rows as the slices being repeated. The first complete row appears twice, followed by two appearances of the second complete row. The column count remains two.

The call np.repeat(a,2,axis=1) returns [[8,8,3,3],[2,2,9,9]], with shape (2,4). Now columns are repeated, so each row contains adjacent pairs. The number of rows remains two. Because the input is square, its original shape does not identify which direction will grow. The axis argument and the resulting shape show which dimension changed.

State the default flattening rule

If axis is omitted, NumPy uses the flattened input and returns a flat output. For our matrix, np.repeat(a,2) returns [8,8,3,3,2,2,9,9], with shape (8,). It does not preserve the two dimensional layout. That differs from explicitly repeating along either matrix axis, even though all three calls copy the same supplied values.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, repetition counts and axis before writing the result. Then follow one original entry or complete slice through its output group. These checks distinguish consecutive repetition from pattern repetition and keep copied data separate from genuinely new observations.