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 clip limits array values to chosen bounds without removing positions

Limiting values to an interval is different from selecting only the values already inside it. NumPy clip replaces entries outside chosen bounds with the corresponding endpoints. Academia Master Trader presents this English lesson for readers in Libya, using constructed arrays to explain clipping, one sided limits and the effect of writing the result into the original array.

Values outside the interval become endpoints

After import numpy as np, define v = np.array([-4,2,6,13]). The call np.clip(v,0,10) returns [0,2,6,10]. Negative four becomes zero because it lies below the lower bound. Thirteen becomes ten because it exceeds the upper bound.

Two and six stay unchanged because they already lie inside the interval. A value exactly equal to either bound also remains unchanged. Clipping does not remove positions, reorder entries or shorten this vector. It changes the values that cross the supplied limits.

NumPy clipping bounds

Clipping is not filtering or rescaling

The output still has four entries, one for every input position. Selecting only entries within the interval would instead return [2,6] for this example. That selection answers a different question because it excludes positions rather than replacing their values.

Clipping also does not proportionally rescale the entire input range into the target interval. Two stays two and six stays six. Several different values above ten would all become ten, so the clipped output alone would not reveal their original magnitudes.

Keep the source alongside the transformed result when the original values matter. Stating both bounds makes the transformation easier to interpret and avoids confusing a limit with a selection condition.

None leaves one boundary unrestricted

The call np.clip(v,0,None) returns [0,2,6,13]. Only the lower limit is applied, so thirteen remains thirteen. The call np.clip(v,None,10) returns [-4,2,6,10], applying only the upper limit.

These calls use None to indicate that no clipping should occur on that side. None is not another numeric endpoint and does not mean zero. Check which argument holds None before describing the direction of the limit.

A matrix keeps its shape with scalar bounds

For m = np.array([[-3,4],[12,7]]), the call np.clip(m,0,9) returns [[0,4],[9,7]], with shape (2,2). The same scalar bounds apply independently at every position.

By default, this call returns a result without changing m. The optional output argument can change that behaviour. Using np.clip(m,0,9,out=m) writes the clipped values into m itself. Make that choice explicit whenever later calculations will reuse the source array.

For this matrix, two entries change and two entries remain the same. Compare corresponding input and output positions rather than comparing sorted value lists. This keeps the explanation tied to the original arrangement of rows and columns.

Bound order is part of the calculation

NumPy does not check that the lower bound is smaller than the upper bound. The call np.clip(v,10,0) returns [0,0,0,0]; it does not exchange the bounds. Confirm their intended order before interpreting the output.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the bounds and whether the source is preserved beside every clipping operation.

NumPy digitize assigns interval indices while keeping boundary rules explicit

A sequence of boundaries can describe intervals without changing the original observations. NumPy digitize reports which interval index corresponds to each input value. Academia Master Trader presents this English lesson for readers in Yemen, using constructed numeric arrays to explain increasing boundaries, endpoint inclusion and the difference between interval labels and interval counts.

Increasing boundaries define adjacent intervals

After import numpy as np, define edges = np.array([0,10,20,30]) and x = np.array([4,10,17,30]). The call np.digitize(x,edges) returns [1,2,2,4].

With increasing boundaries and the default right=False, index i describes edges[i-1] <= value < edges[i] for an interior interval. Four belongs to interval one, between zero inclusive and ten exclusive. Ten and seventeen belong to interval two, between ten inclusive and twenty exclusive.

The output numbers are interval indices. They are not the input values, interval widths or counts of observations. Two observations receive index two here, but digitize does not replace that pair with a frequency count.

NumPy interval boundaries

The right argument changes which endpoint is included

The call np.digitize(x,edges,right=True) returns [1,1,2,3]. For increasing boundaries, an interior interval now follows edges[i-1] < value <= edges[i]. Ten belongs to interval one rather than interval two.

Thirty also changes its result. Under the default rule, thirty is not inside the final interior interval because that interval excludes its right endpoint. With right set to True, thirty belongs to interval three, which includes thirty and excludes twenty.

Four and seventeen do not sit on the boundaries, so their interval indices remain unchanged. Compare exact endpoint values separately from values strictly between boundaries when explaining this argument.

Values beyond the boundary range need separate handling

The call np.digitize([-3,35],edges) returns [0,4]. Zero and the number of boundaries are possible results for values outside the covered interior intervals. They should not be mistaken for ordinary interior intervals with two available endpoints.

For example, using returned index four directly as edges[4] would exceed this array's valid element indices. Before retrieving lower and upper boundaries, separate results that fall at the outer index values. The rule should match the intended treatment of values beyond the supplied range.

Digitize does not change either the observations or the supplied boundaries. Keeping both arrays beside the labels makes a simple verification possible: inspect one observation, locate its neighbouring boundaries and apply the chosen inequality. Repeat that reasoning for boundary values separately.

Input shape is preserved and boundaries must be monotonic

The call np.digitize([[4,17],[10,25]],edges) returns [[1,2],[2,3]]. The output has the same shape as the input values, so each interval label remains aligned with its original observation.

Boundaries must form a one dimensional monotonic sequence. Decreasing boundaries are supported, but their interval inequalities differ from the increasing example. An unordered boundary sequence raises ValueError; digitize does not silently sort it. Keep the boundary direction visible when describing any result.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the boundary sequence and endpoint rule beside every set of interval indices.

NumPy searchsorted finds insertion positions without changing the source array

A sorted sequence can answer where a new value belongs before any insertion is performed. NumPy searchsorted returns positions that preserve ascending order. Academia Master Trader presents this English lesson for readers in Syria, using constructed arrays to explain insertion boundaries, repeated values and the meaning of positions returned with a sorter.

The result is a position rather than an updated array

After import numpy as np, define a = np.array([3,7,7,12]). The call np.searchsorted(a,9) returns 3. Inserting nine before position three would place it between the final seven and twelve.

Searchsorted does not insert nine. The original array remains [3,7,7,12]. Its result is an integer identifying an insertion point. Distinguish that position from the input value and from any later array that a separate insertion operation might create.

NumPy insertion boundaries

Left and right choose opposite boundaries of equal values

The call np.searchsorted(a,7,side='left') returns 1. The left boundary comes before both existing sevens. This is also the default side, so np.searchsorted(a,7) produces the same result.

The call np.searchsorted(a,7,side='right') returns 3. The right boundary comes after both sevens and before twelve. Both positions preserve sorted order. The side argument determines how the new value is placed relative to entries equal to it.

For a value absent from the array, left and right can agree. Both sides return three for nine in this example because there is no group of equal nines separating the boundaries. Write the repeated values beside each boundary when explaining why the answers differ.

Endpoint positions are valid insertion locations

The call np.searchsorted(a,[1,7,15]) returns [0,1,4]. One belongs before the first entry. Seven uses the default left boundary. Fifteen belongs after the final entry.

Position four is a valid insertion point for an array of length four, but it is not an existing element index. Reading a[4] would be outside the array. A boundary result must not automatically be used to retrieve an existing value without checking whether it lies within the element range.

When the query values form an array, the returned positions have that query array's shape. Each query is located against the same source sequence; the queries are not inserted one after another while the source grows.

For example, np.searchsorted(a,[[1,9],[7,15]]) returns [[0,3],[1,4]]. This two by two result keeps the arrangement of the query values. The source remains a one dimensional sequence even when the query contains several dimensions.

A sorter refers to a sorted view of the positions

Without a sorter, the source must already be sorted in ascending order. For b = np.array([12,3,7,7]), define order = np.argsort(b). The call np.searchsorted(b,9,sorter=order) returns 3.

That result belongs to the sorted sequence b[order], which is [3,7,7,12], not directly to the original arrangement of b. Supplying a sorter does not rearrange b. Keep the original positions and sorted positions distinct throughout the explanation.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the sorted source, query value and side before interpreting an insertion boundary.

NumPy argwhere groups each selected element's coordinates into one row

Sometimes a coordinate table is easier to read than separate arrays of row and column indices. NumPy argwhere reports the positions of nonzero entries, with one coordinate row for each qualifying element. Academia Master Trader presents this English lesson for readers in Afghanistan, using constructed arrays to explain this layout and its distinction from direct array indexing.

Each output row describes one input position

After import numpy as np, define m = np.array([[0,6,0],[9,0,12]]). The call np.argwhere(m) returns [[0,1],[1,0],[1,2]]. Each row contains a row index followed by a column index because the input has two dimensions.

The first coordinate row locates six at row zero, column one. The second locates nine at row one, column zero. The third locates twelve at row one, column two. Coordinates count from zero and describe positions, not the numeric values stored at those positions.

NumPy coordinate table

Output shape combines the match count and input dimensions

The result has shape (3,2): three qualifying elements and two coordinates per element. More generally, its shape is (N,a.ndim), where N is the number of nonzero entries and a is the input array.

For v = np.array([0,-5,0,8]), the call np.argwhere(v) returns [[1],[3]], with shape (2,1). A vector needs only one coordinate per selected position, but the output still has a coordinate column. Negative five qualifies because it is nonzero; the function does not restrict selection to positive numbers.

The number of output rows and columns answers different questions. Rows count selected positions. Columns count the coordinates needed to locate one element in the original input. Neither dimension represents an average or a sum of the selected values.

For a three dimensional input, every coordinate row would contain three indices. The same reading rule applies: each index belongs to the corresponding input axis. Keep the input shape beside the coordinate table when explaining arrays with more than two dimensions.

Conditions can define the positions to report

The call np.argwhere(m > 8) returns [[1,0],[1,2]]. The comparison creates a Boolean condition array first. Argwhere then reports positions where that condition is True. Those coordinate rows identify nine and twelve in the original matrix.

For np.argwhere(m == 0), the result is [[0,0],[0,2],[1,1]]. This locates zeros by applying argwhere to the equality condition, rather than asking argwhere to treat zero as a nonzero input value. Distinguish the original matrix from the condition array that the function actually receives.

A coordinate table is not a direct indexing tuple

Do not assume that m[np.argwhere(m)] retrieves the listed nonzero values. Argwhere's output groups coordinates into rows and is not suitable as a direct array index for that purpose. Use m[np.nonzero(m)] or m[m != 0] to obtain [6,9,12].

If no entries qualify, the coordinate table has zero rows while retaining a column for each input dimension. For this two dimensional matrix, np.argwhere(m > 20) has shape (0,2).

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Read each coordinate row as one location and choose a suitable indexing expression when values are needed.

NumPy nonzero returns coordinate arrays rather than the values at those positions

An array can contain useful positional information even when many entries equal zero. NumPy nonzero identifies the positions whose entries are nonzero. Academia Master Trader presents this English lesson for readers in Iran, using constructed arrays to explain coordinate tuples, row major order and the difference between locating entries and retrieving their values.

A vector produces a tuple containing one index array

After import numpy as np, define v = np.array([0,7,0,-4,9]). The call np.nonzero(v) returns a tuple containing the index array [1,3,4]. NumPy counts positions from zero. Seven occupies position one, negative four occupies position three and nine occupies position four.

The negative value is included because nonzero does not mean positive. Both positive and negative entries qualify when they differ from zero. The returned numbers are indices, not copies of seven, negative four and nine. Keep the location result separate from the input values when explaining the operation.

NumPy coordinate selection

A matrix produces one coordinate array for each dimension

Define m = np.array([[0,5,0],[8,0,11]]). The call np.nonzero(m) returns ([0,1,1],[1,0,2]), with each displayed list representing an array inside the returned tuple. The first array contains row indices and the second contains column indices.

Read corresponding positions together. The first pair is row zero, column one, which locates five. The second pair is row one, column zero, which locates eight. The third pair is row one, column two, which locates eleven.

Do not read the first array as one complete coordinate and the second array as another. Nonzero groups indices by dimension. It does not return one row per located element. With a three dimensional input, the tuple has three coordinate arrays instead of two.

The reported positions follow row major order

For this matrix, the scan visits the first row before the second row. Within each row, it visits columns from left to right. The resulting coordinate sequence is therefore (0,1), (1,0), (1,2).

Assign locations = np.nonzero(m). The expression m[locations] returns [5,8,11]. This second operation retrieves the values at the reported coordinates. When the goal is simply to select nonzero values, m[m != 0] is a direct alternative.

Each coordinate array has the same length, equal to the number of qualifying entries. Here that length is three. Preserving this shared order lets NumPy combine the arrays into valid coordinates during indexing without forming every possible row and column combination.

A condition can define which positions to locate

The expression np.nonzero(m > 7) returns coordinate arrays [1,1] and [0,2]. The condition first creates a Boolean array. True entries identify the positions of eight and eleven, so those are the positions reported.

An input containing only zeros still produces a tuple with one empty index array per input dimension. For a zero matrix with shape (2,3), both coordinate arrays are empty. Their emptiness means no positions qualified; it does not change the number of input dimensions.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Pair coordinate entries by their shared position and distinguish indices from selected values.

NumPy compress selects array positions using a one dimensional condition

A condition can describe which positions to keep without listing their integer indices. NumPy compress uses a one dimensional condition to select entries or whole slices from an array. Academia Master Trader presents this English lesson for readers in Turkey, using constructed arrays to explain the relationship between a condition, an axis and the resulting shape.

True keeps a position and False leaves it out

After import numpy as np, define v = np.array([6,12,18,24]). The call np.compress([True,False,True,False],v) returns [6,18]. Each condition entry corresponds to a position in the input. The selected values retain their original order.

The condition is a positional instruction, not a list of values to find. True in the third position keeps eighteen because eighteen occupies that position. Compress does not reorder the selected positions or repeat them. To request positions in a different order, use an integer index operation such as take instead.

NumPy condition selection

A selected axis determines the size of each retained slice

Define m = np.array([[2,5,8],[11,14,17]]). The call np.compress([True,False,True],m,axis=1) returns [[2,8],[11,17]], with shape (2,2). The condition keeps the first and third columns across both rows.

The same idea applies to rows. The call np.compress([False,True],m,axis=0) returns [[11,14,17]], with shape (1,3). One True entry retains one complete row. The result still has a row axis even though only one row remains.

These examples illustrate why an axis belongs beside every condition when explaining a matrix selection. A condition attached to columns has a different meaning from one attached to rows. Read the selected axis length before interpreting the condition's positions.

An omitted axis refers to a flattened sequence

The call np.compress([False,True,False,True,False,True],m) returns [5,11,17]. With no axis argument, NumPy selects individual entries from the flattened input. It does not preserve the original two by three matrix shape.

The flattened order here is [2,5,8,11,14,17]. Writing that sequence beside the condition makes each choice explicit. The three True positions select five, eleven and seventeen in that order. No averaging or addition is involved.

A shorter condition limits the positions considered

The call np.compress([True,False],v) returns [6]. It considers only the first two positions. The later entries eighteen and twenty four are not automatically retained or covered by repeating the condition.

For a matrix, np.compress([True,False],m,axis=1) returns [[2],[11]], with shape (2,1). Again, the third column is outside the shorter condition. Matching condition length to the selected axis length can make the intended coverage easier to inspect.

A condition can be calculated from values before calling compress. For this vector, v > 12 gives [False,False,True,True], and np.compress(v > 12,v) returns [18,24]. First explain how the condition was formed, then explain which positions it retains.

Compress returns a copy. An all False condition selects no entries along the chosen axis; for example, np.compress([False,False],m,axis=0) has shape (0,3). The empty row axis does not remove the three column dimension.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the condition, axis and expected output shape together.

NumPy take selects array entries in the order specified by integer indices

Selecting positions does not require those positions to be consecutive or sorted. NumPy take gathers entries using integer indices and an optional axis. Academia Master Trader presents this English lesson for readers in Israel, using constructed arrays to explain selection order, repeated indices and how the shape of the index array affects the result.

The index list determines the output order

After import numpy as np, define v = np.array([4,9,14,19]). The call np.take(v,[3,0,2]) returns [19,4,14]. NumPy counts positions from zero, so index three selects nineteen and index zero selects four.

The output follows the supplied indices, not the original numerical order. The call does not sort the source values. An index describes a position rather than a target value: asking for index two selects fourteen, not the number two. Keep these two meanings separate when reading a selection expression.

NumPy indexed selection

Repeated indices produce repeated selections

The call np.take(v,[1,1,0]) returns [9,9,4]. The same input position can contribute more than once. This is useful for understanding that take follows an explicit positional recipe rather than collecting a set of unique values.

A negative index is valid under the default mode when it falls within the input bounds. For example, np.take(v,[-1,0]) returns [19,4]. Negative one refers to the final position. An index beyond the allowed range raises IndexError under the default mode.

An axis selects corresponding slices of a matrix

Define m = np.array([[2,5,8],[11,14,17]]). The call np.take(m,[2,0],axis=1) returns [[8,2],[17,11]], with shape (2,2). It selects column two and then column zero across both rows.

Using np.take(m,[1,0],axis=0) instead returns [[11,14,17],[2,5,8]]. Whole rows are selected in the requested order. Both the index sequence and the chosen axis are necessary to describe which entries appear and how they are arranged.

Without an axis, positions refer to the flattened input

The call np.take(m,[3,0]) returns [11,2]. With axis omitted, NumPy uses the flattened input sequence. Position three is eleven in that sequence, even though the matrix has only two rows.

The index array can also have its own dimensions. The call np.take(v,[[0,3],[2,1]]) returns [[4,19],[14,9]], with shape (2,2). For a selected axis, the index array's shape replaces that axis in the output shape, while the surrounding source axes remain.

A scalar index and a one entry index list also describe different shapes. Selecting np.take(m,1,axis=0) returns a row shaped vector with shape (3,). Selecting np.take(m,[1],axis=0) keeps the index list dimension and returns shape (1,3). The values match, but the dimensional structure differs.

Choose boundary behaviour deliberately

Take supports raise, wrap and clip modes. With this four entry vector, np.take(v,[4],mode='wrap') returns [4], while np.take(v,[4],mode='clip') returns [19]. Wrap returns around the boundary; clip limits an excessive index to an endpoint.

Clip also changes negative index behaviour: np.take(v,[-1],mode='clip') returns [4], not [19]. State the mode explicitly when boundary handling is part of the intended calculation.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the index order, axis and mode beside every selection result.

NumPy repeat places repeated entries together along a selected axis

Repeating individual entries creates a different order from repeating a complete pattern. NumPy repeat places the requested number of occurrences of each entry together. Academia Master Trader presents this English lesson for readers in Palestine, using constructed arrays to explain uniform counts, different counts for different positions and the effect of choosing an axis explicitly.

Begin with one count for every vector entry

After import numpy as np, define v = np.array([3,7,11]). The call np.repeat(v,2) returns [3,3,7,7,11,11], with shape (6,).

Each input entry appears twice in succession. The result is not [3,7,11,3,7,11], which would repeat the whole sequence as a pattern. Write the intended output order before choosing between entry repetition and pattern tiling. The same total number of positions does not make those arrangements equivalent.

NumPy entry repetition

Counts can differ across positions

The call np.repeat(v,[1,2,3]) returns [3,7,7,11,11,11]. Three appears once, seven appears twice and eleven appears three times. Each count corresponds to the input position in the same order.

The counts describe total occurrences in the result, not additional copies beyond the original. A count of one therefore keeps one occurrence. A count of zero contributes no occurrence from that position. For example, np.repeat(v,[1,0,2]) returns [3,11,11]. Sum the counts to check the output length in this one dimensional case.

An explicit axis preserves the other dimensions

Define m = np.array([[2,5],[8,11]]). The call np.repeat(m,2,axis=1) returns [[2,2,5,5],[8,8,11,11]], with shape (2,4).

Axis one identifies column positions in this matrix. Each position is repeated along that axis, while the two row positions remain. Using np.repeat(m,2,axis=0) instead gives [[2,5],[2,5],[8,11],[8,11]], with shape (4,2). Whole rows repeat because the chosen axis is now the row axis.

Different row counts repeat complete row slices

The call np.repeat(m,[1,2],axis=0) returns [[2,5],[8,11],[8,11]], with shape (3,2). The first row occurs once and the second row occurs twice.

This example shows why the axis is part of the meaning, not just an optional formatting detail. Counts correspond to positions along that axis. Every slice attached to a repeated position moves together, so the two values within the second row retain their order in both occurrences.

For the row count example, adding one and two gives three output rows, each still containing two entries. For the uniform column example, each of the two input columns contributes two positions, giving four columns. These small checks connect the count parameters to the dimensions instead of relying only on a printed result.

Omitting axis produces a flat result

The call np.repeat(m,2) returns [2,2,5,5,8,8,11,11], with shape (8,). NumPy uses the flattened input and returns a flat output when axis is omitted. It does not restore the original matrix shape afterward.

Keep the output shape beside the repeated values, especially when the next calculation expects rows and columns. Repetition changes the number of positions; it does not add the repeated numbers together or calculate a new value for them.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the counts, selected axis and output order whenever you explain a repeated array.

NumPy tile repeats an array pattern according to a repetition count for each axis

Repeating a whole pattern is different from repeating each individual entry. NumPy tile constructs an array from repeated copies of an input pattern, with repetition counts assigned to axes. Academia Master Trader presents this English lesson for readers in Lebanon, using constructed arrays to explain the output order, shape calculation and dimensional promotion rules.

Repeat a vector as a complete sequence

After import numpy as np, define v = np.array([2,5,8]). The call np.tile(v,2) returns [2,5,8,2,5,8], with shape (6,).

The sequence two, five, eight appears twice. The operation does not produce [2,2,5,5,8,8], which would repeat each entry beside itself. Identify the unit being repeated before choosing a function: tile repeats the input pattern along an axis rather than grouping duplicate copies of each individual value.

NumPy pattern tiling

A tuple supplies counts for several axes

The call np.tile(v,(2,2)) returns [[2,5,8,2,5,8],[2,5,8,2,5,8]], with shape (2,6). The second repetition count doubles the sequence horizontally, while the first produces two rows.

Because the input is one dimensional and the repetition tuple has two entries, NumPy first treats the vector as having shape (1,3). It prepends a length one axis. Multiplying those axis lengths by the corresponding repetition counts gives two by six, matching the output shape.

A short count is aligned with the trailing axes

Define m = np.array([[1,4],[7,10]]), with shape (2,2). The call np.tile(m,2) returns [[1,4,1,4],[7,10,7,10]], with shape (2,4).

A single repetition count does not double every axis. Since the input has two dimensions, the count is treated as (1,2): one copy along the first axis and two along the second. To repeat the matrix vertically instead, use np.tile(m,(2,1)), which gives shape (4,2) and rows [1,4], [7,10], [1,4], [7,10].

Longer tuples can introduce leading axes

The call np.tile(v,(2,1,2)) has shape (2,1,6). The vector is treated as shape (1,1,3) before the repetition counts are applied. The result has two leading blocks, each containing one row of the sequence repeated twice.

This is dimensional promotion, not transposition. Existing axes keep their relative order. When a different arrangement is intended, reshape the input deliberately before tiling rather than expecting the repetition tuple to exchange axes. Write the promoted input shape beside the counts to make the output dimensions easier to follow.

For a simple size check, the vector has three entries and two copies contain six entries. For the matrix, the (2,1) counts produce two complete copies of a four entry input, giving eight positions. This count complements the shape calculation without replacing the need to track each axis separately.

Keep the purpose of replication clear

Tile constructs a repeated output array. When the goal is only to combine compatible shapes during arithmetic, NumPy's documentation recommends broadcasting operations instead of using tile to imitate broadcasting. These are related ideas, but they are not interchangeable descriptions of the same task.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the repeated pattern, aligned repetition counts and resulting shape before passing a tiled array to another calculation.

NumPy roll moves entries cyclically while preserving the array shape

A cyclic shift returns entries to the beginning after they pass the end of a sequence. NumPy roll performs this positional operation along a chosen axis, or across a flattened array when no axis is supplied. Academia Master Trader presents this English lesson for readers in Egypt, using constructed data to distinguish wraparound from padding and from reversing the order.

Start with a vector and one positive shift

After import numpy as np, define v = np.array([3,6,9,12,15]). The call np.roll(v,2) returns [12,15,3,6,9]. Every entry moves two places toward higher indices, with the final two entries wrapping to the beginning.

No zero is inserted and no entry is discarded. The output still has shape (5,). The relative cyclic order remains intact: after fifteen comes three when the sequence is read around its boundary. This differs from sorting or reversing the vector.

NumPy cyclic shift

A negative shift moves in the opposite direction

The call np.roll(v,-1) returns [6,9,12,15,3]. Three moves past the beginning and reappears at the end. The sign controls the direction, while the magnitude gives the number of positions.

For this five entry vector, shifting by five restores the original arrangement. Shifting by seven gives the same arrangement as shifting by two. Count positions around the sequence rather than treating a large shift as a request to create extra entries or change the output length.

Choose an axis for a matrix

Define m = np.array([[2,4,6],[8,10,12]]). The call np.roll(m,1,axis=1) returns [[6,2,4],[12,8,10]]. Each row wraps its last entry to its own beginning.

Using np.roll(m,1,axis=0) instead returns [[8,10,12],[2,4,6]]. Whole rows move along the first axis, while the order inside each row remains unchanged. Both results have shape (2,3). The same shift value can therefore describe different positional movements depending on the selected axis.

Omitting axis changes how positions are grouped

The call np.roll(m,1) returns [[12,2,4],[6,8,10]]. NumPy first flattens the input, rolls that sequence and then restores the original shape.

Here six crosses the former row boundary, and twelve wraps from the final position to the very beginning. This is not the same as rolling every row independently. Shape alone cannot tell you whether an axis was supplied, because both versions restore or retain the matrix shape. Record the call parameters beside the output.

A useful manual check is to label the positions before moving the values. For the vector, position zero moves to position two under a positive shift of two. Following one position and one boundary crossing makes the direction clear without relying on the numeric size of any entry.

Several axes can have different shifts

The call np.roll(m,shift=(1,1),axis=(0,1)) returns [[12,8,10],[6,2,4]]. The shift tuple pairs each amount with the axis in the corresponding position. One shift moves the rows, and the other moves the columns cyclically.

The operation describes where existing entries go. It does not add values together, interpolate between them or introduce blank space at the edge. Choose another operation when those are the intended effects.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the shift, axis choice and wraparound rule whenever you explain a rolled array.