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 squeeze removes length one dimensions without deleting numeric entries

A dimension of length one can express a useful grouping, even when it contains no variation along that axis. When an operation requires fewer dimensions, NumPy squeeze can remove selected singleton axes. Academia Master Trader presents this English lesson for readers in the Philippines, using constructed arrays to explain the default behavior, explicit axis selection and the difference between a zero dimensional array and an ordinary number.

Separate axis lengths from stored entries

After import numpy as np, define a = np.array([[[3],[6],[9]]]). Its shape is (1,3,1). There are three dimensions and three numeric entries. The first and final dimensions each have length one, while the middle dimension has length three.

The call np.squeeze(a) returns [3,6,9], with shape (3,). By default, the function removes all length one dimensions. The entries three, six and nine remain present and keep their order. Reducing the number of dimensions is not the same as deleting observations from the data.

NumPy squeeze

Select the singleton dimension to remove

The call np.squeeze(a,axis=0) gives [[3],[6],[9]], with shape (3,1). It removes the leading dimension and leaves the final length one dimension in place. The output is a column shaped matrix rather than a one dimensional vector.

The call np.squeeze(a,axis=2) gives [[3,6,9]], with shape (1,3). It removes the final dimension but keeps the leading one. These two outputs contain the same entries, yet their shapes express different two dimensional arrangements. Name the retained axes when a later calculation expects one particular structure.

A longer dimension cannot be squeezed away

The call np.squeeze(a,axis=1) raises ValueError because source axis one has length three. Squeeze does not choose one of those three entries, combine them into a total or discard that dimension by removing values. An explicitly selected axis must have length one.

This condition makes the intended structural change clear. If the goal is a summary or a selection, use an operation that expresses that goal instead. A smaller number of dimensions can arise through several different operations, and the output shape alone does not explain what happened to the entries.

Several singleton axes can be named together

The call np.squeeze(a,axis=(0,2)) returns the same one dimensional arrangement as the default call in this example. It explicitly identifies the two singleton dimensions in the source shape. The middle length three axis is retained.

An explicit selection also records which structural assumptions the calculation depends on. The function will not silently remove a selected axis that has become longer than one. Keep the original shape beside the axis selection when explaining why a particular dimension can be removed.

Removing every axis still leaves an array

Define z = np.array([[12]]), with shape (1,1). The call q = np.squeeze(z) has shape (). The result is a zero dimensional array containing twelve, not an ordinary Python scalar. It has one numeric entry and no axes.

The documentation states that the result is the input itself or a view into it. With the original a, set s = np.squeeze(a). Writing s[1] = 99 also changes a[0,1,0] to ninety nine. Use an explicit copy when later edits must stay separate. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record removed axis positions and the resulting shape without confusing dimensionality with entry count.

Adding a singleton axis in NumPy changes dimensional structure without adding entries

A one dimensional array and a matrix can contain the same values while having different shapes. Some calculations require an explicit row, column or extra grouping dimension. NumPy provides a function that inserts an axis of length one at a chosen position. Academia Master Trader presents this English lesson for readers in Taiwan, using constructed examples to distinguish a new dimension from new observations and to make the resulting shapes clear.

Begin with a one dimensional array

After import numpy as np, define v = np.array([3,6,9]). Its shape is (3,), so it has one dimension containing three entries. The call r = np.expand_dims(v,axis=0) gives [[3,6,9]], with shape (1,3). The new leading axis has length one.

The entries remain three, six and nine. A second dimension has appeared, but no additional numeric entries have been recorded. The output can be described as one row containing three columns. That description depends on the two dimensional shape, not merely on the values printed inside the array.

NumPy singleton axes

Place the new axis after the original one

The call c = np.expand_dims(v,axis=1) gives [[3],[6],[9]], with shape (3,1). There are now three rows and one column. The same source vector therefore supports two different two dimensional arrangements, depending on where the singleton axis is inserted.

For this source, np.expand_dims(v,axis=-1) also gives shape (3,1). Negative one names the final position in the expanded shape. The axis argument describes the position of the new dimension, not the position of an entry that should be duplicated or moved.

Keep dimension count separate from entry count

The original v has one dimension; r and c each have two. All three arrays contain three entries. Inserting a singleton axis increases dimensionality without increasing the product of the axis lengths. Multiplying by a new length of one leaves that product unchanged.

This distinction is useful when preparing arrays for an operation that expects explicit dimensions. State what each axis means instead of assuming that one extra axis represents an extra measurement. The function changes structure; it does not collect data or manufacture a missing observation.

Several new axes can be requested together

The call np.expand_dims(v,axis=(0,2)) gives shape (1,3,1). The newly inserted dimensions occupy positions zero and two in the expanded result. The original length three dimension sits between them at position one.

The result is [[[3],[6],[9]]]. Reading its shape alongside the brackets makes the arrangement easier to follow. Both new dimensions have length one, and the number of numeric entries is still three. Use an explicit description of the output axes when more than one new position is involved.

A new shape can still share source data

The documentation describes the result as a view with an increased number of dimensions. Starting again from v, set r = np.expand_dims(v,axis=0). Writing r[0,1] = 99 also changes v[1] to ninety nine. The extra dimension does not make later edits independent of the source.

Use an explicit copy when separate editing is required. The call np.squeeze(r,axis=0) removes this length one axis and returns the original one dimensional shape. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the starting shape, inserted axis positions and final shape, keeping the number of dimensions distinct from the number of entries.

NumPy moveaxis relocates a dimension while preserving the relative order of the others

An array can organize the same entries under several dimension orders. Sometimes one dimension needs to move without specifying a complete permutation of every axis. NumPy moveaxis names its source position and destination position. Academia Master Trader presents this English lesson for readers in China, using constructed arrays to explain the resulting shape, coordinate mapping and the difference between moving one axis and exchanging a pair.

Start from three distinct axis lengths

After import numpy as np, define a = np.arange(24).reshape(2,3,4). The shape (2,3,4) records three dimensions with lengths two, three and four. The call b = np.moveaxis(a,0,-1) moves source axis zero to the final position and gives shape (3,4,2).

The other axes keep their relative order. Source axes one and two remain in that order, now followed by source axis zero. All twenty four entries remain present. Moving an axis is not a request to calculate a mean, discard a group or change the numeric values.

NumPy moveaxis

Read the destination as an output position

In the previous call, negative one means the last axis position. The explicit call np.moveaxis(a,0,2) gives the same arrangement for this three dimensional array. It moves the first source dimension to output position two, after the other two dimensions.

The source entry a[1,2,3] is twenty three. In b, that same entry is addressed as b[2,3,1]. The coordinate belonging to source axis zero moves to the end, while the other two coordinates keep their order. This mapping explains the move more precisely than shape alone.

Moving one axis is different from swapping two

The call np.swapaxes(a,0,2) gives shape (4,3,2), not (3,4,2). Swapping exchanges the two selected axes directly. Moving axis zero to the end shifts the intervening dimensions forward while keeping their relative order.

The distinction matters even when the arrays contain the same number of entries. A matching entry count does not establish matching coordinate order. Write the source axis sequence beside each result: moveaxis produces the order (1,2,0), whereas this swap produces (2,1,0).

Move the final axis to the beginning

The call np.moveaxis(a,-1,0) returns shape (4,2,3). It places the final source dimension first, followed by the original first and second dimensions. The remaining two axes keep their order rather than reversing.

For this arrangement, the source entry a[1,2,3] appears at output position [3,1,2]. Naming the data meaning of each dimension helps interpret that mapping. An axis length by itself does not reveal whether the dimension represents time, a category, a channel or another recorded feature.

A view can expose the same underlying entries

The documentation describes the result as a view of the input array. Starting again from a, set b = np.moveaxis(a,0,-1). Writing b[2,3,1] = 99 also changes a[1,2,3] to ninety nine. The new axis order does not make later edits independent of the source.

Use an explicit copy when separate editing is needed. To undo this particular move, np.moveaxis(b,-1,0) restores the original axis order. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source axis, destination position and resulting shape, and keep separately stored dimension labels aligned with their new positions.

NumPy swapaxes exchanges two array dimensions while keeping every entry accounted for

A numeric array can describe several dimensions at once. Moving two of those dimensions changes the coordinate order used to find each entry, rather than calculating new numeric values. NumPy swapaxes names the two axes to exchange. Academia Master Trader presents this English lesson for readers in South Korea, using constructed arrays to connect axis numbers, output shape and the source position of a relocated entry.

Begin with a row that already has two dimensions

After import numpy as np, define r = np.array([[3,6,9]]). The doubled brackets create a two dimensional array with shape (1,3). The call np.swapaxes(r,0,1) returns [[3],[6],[9]], with shape (3,1). The row axis and column axis exchange positions.

All three entries remain present. The output has three rows and one column instead of one row and three columns. The operation does not divide each value, sort the values or insert extra observations. It changes which coordinate describes the row and which describes the column.

NumPy swapaxes

Axis numbers are not entry positions

The arguments zero and one refer to dimensions, not to the first two numeric entries. In the previous example, swapping axes does not mean exchanging three with six while leaving nine where it was. It exchanges the roles of the two dimensions of the complete array.

A one dimensional array such as np.array([3,6,9]) has only axis zero. It does not have an existing axis one to exchange with axis zero. If the intended result needs an additional dimension, create that dimension explicitly before choosing which axes to exchange.

Follow a three dimensional shape

Define a = np.arange(24).reshape(2,3,4). Its three axis lengths are two, three and four. The call s = np.swapaxes(a,0,2) gives an array with shape (4,3,2). Axis zero and axis two exchange positions, while axis one keeps its place in the order.

This example contains twenty four entries before and after the exchange. It does not become a smaller sample or a summary. A change from two leading groups to four leading groups describes a different arrangement of dimensions, not an increase in the amount of recorded information.

Trace coordinates through the exchange

The source entry a[1,2,3] is twenty three. After exchanging axes zero and two, the same entry is at s[3,2,1]. The outer coordinates exchange roles; the middle coordinate remains two. Following the coordinate mapping explains the movement more clearly than relying only on a printed block of numbers.

The call np.swapaxes(s,0,2) restores the original arrangement. Exchanging the same pair twice returns the dimensions to their starting order. This is an arrangement check, not a claim that independently stored labels or other records have also been moved.

Shared storage matters during later editing

For a NumPy ndarray in current versions, the documented result is a view. Starting again from a, set s = np.swapaxes(a,0,2). Writing s[3,2,1] = 99 also changes a[1,2,3] to ninety nine. Two coordinate arrangements can address the same underlying data.

Use an explicit copy when later changes must stay separate. Give each source axis a clear meaning before exchanging it, and carry that meaning into the output labels. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the exchanged pair, original shape and resulting shape so another reader can trace each dimension without guessing.

NumPy transpose changes axis order without turning a one dimensional array into a column

An axis describes one dimension of an array. Exchanging axis order changes how positions are addressed, rather than changing the numeric meaning of each entry. NumPy transpose makes that distinction visible in a small matrix and becomes especially useful when an array has several dimensions. Academia Master Trader presents this English lesson for readers in Japan, using constructed examples to separate axis permutation, matrix shape and the addition of a new dimension.

Exchange the two axes of a matrix

After import numpy as np, define m = np.array([[1,4,7],[2,5,8]]). Its shape is (2,3): two rows and three columns. The call np.transpose(m) returns [[1,2],[4,5],[7,8]], with shape (3,2). The first source row becomes the first output column, while the second source row becomes the second output column.

The original entry m[0,2] is seven. After transposing, the corresponding entry is at position [2,0]. The two coordinates exchange roles. All six entries remain present, and none is multiplied, averaged or sorted. The shorter expression m.T gives the same matrix transpose for this two dimensional array.

NumPy transpose

Transposing is different from a quarter turn

The transposed result begins with [1,2]. A counterclockwise quarter turn of this same matrix would begin with [7,8]. Both arrangements have shape (3,2), but their values occupy different positions. A shared shape is not enough to show that two transformations are equivalent.

Follow a known source entry through its coordinates when explaining the operation. For a matrix transpose, exchanging the row and column coordinates gives the destination. This positional account is more precise than saying that the matrix was simply turned, because a turn can imply a different rearrangement.

A single axis has no second axis to exchange

Define v = np.array([3,6,9]). Its shape is (3,), meaning it has one axis. The call np.transpose(v) still has shape (3,) and the same three entries. Writing v.T does not create a two dimensional column matrix either.

To form a column explicitly, use v[:,np.newaxis]. The result is [[3],[6],[9]], with shape (3,1). That expression adds an axis. Adding a dimension and reordering existing dimensions are separate operations, even if printed outputs sometimes make them look similar.

Specify where each source axis goes

For a three dimensional example, define a = np.arange(24).reshape(2,3,4). The call np.transpose(a,axes=(1,0,2)) returns an array with shape (3,2,4). Output axis zero corresponds to source axis one, output axis one corresponds to source axis zero, and output axis two still corresponds to source axis two.

Without an axes argument, transpose reverses the complete axis order. For a, that default gives shape (4,3,2). An explicit axis order must be a permutation of the existing axes: each source axis appears once. It is not a list of selected entries or a request to discard a dimension.

Track shared data as well as shape

The documentation states that a view is returned whenever possible. For the ordinary matrix in this lesson, the transposed arrangement can share data with its source. Starting again from m, set t = np.transpose(m). Writing t[2,0] = 99 also changes m[0,2] to ninety nine.

Use an explicit copy when independent editing is needed. Keep separately stored row and column labels aligned with their new roles. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source shape, requested axis order and output shape to make the positional change clear.

NumPy rot90 turns an array in quarter rotations within a chosen pair of axes

A quarter turn rearranges positions across two axes. It does not multiply values by ninety or calculate an angle for every entry. NumPy rot90 expresses that rearrangement with a rotation count and a pair of axes. Academia Master Trader presents this English lesson for readers in Thailand, using a small constructed matrix to make each moved position and each resulting shape easy to follow.

Follow the first quarter turn

After import numpy as np, define m = np.array([[1,4,7],[2,5,8]]). This matrix has two rows and three columns, so its shape is (2,3). The call np.rot90(m) returns [[7,8],[4,5],[1,2]]. With the default axis pair and rotation count, the two dimensional arrangement turns counterclockwise by ninety degrees.

The final source column, containing seven and eight, becomes the first output row. The first source column, containing one and two, becomes the final output row. There are still six entries, but the resulting shape is (3,2). A quarter turn can change an array's shape without adding or removing entries.

NumPy rot90

Count quarter turns rather than degrees

The argument k counts ninety degree turns. The call np.rot90(m,k=2) returns [[8,5,2],[7,4,1]], which is a half turn of the original arrangement. Its shape is (2,3), the same as the input. The values have moved even though the shape has returned to the original pair of lengths.

The call np.rot90(m,k=4) restores the original arrangement after four quarter turns. Passing k=90 does not request a ninety degree turn. It requests ninety quarter turns. Keeping the unit of the argument explicit prevents a number that looks familiar from expressing a different operation.

Reverse the direction with a negative count

The call np.rot90(m,k=-1) returns [[2,1],[5,4],[8,7]]. For this default plane, a negative quarter turn goes clockwise. Its output also has shape (3,2), but its entries differ from the positive quarter turn.

Shape alone cannot identify the direction used. Compare a known corner or a complete row with the source when explaining the result. In this example, two moves from the lower left source corner to the upper left output corner under the clockwise turn.

Keep the axis order explicit

The default axis pair is (0,1). Reversing that pair reverses the direction: np.rot90(m,axes=(1,0)) gives the same arrangement as np.rot90(m,k=-1). Both calls make the clockwise quarter turn shown above.

The two axes must be different. For an array with more than two dimensions, the selected pair defines the plane of the turn. Name those dimensions before using the operation, because an axis number does not explain whether it represents rows, columns, layers or another recorded dimension.

A rotated view can share the original data

The documentation describes the result as a rotated view. With an ordinary NumPy array, that means the result can share underlying data with its source rather than hold a separate set of entries. The rearrangement itself does not replace the input values, but writing through the returned view can affect the original array.

Starting again from m, set r = np.rot90(m). Writing r[0,0] = 99 also changes m[0,2] to ninety nine. Use an explicit copy when independent editing is required. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the axis pair, quarter turn count and resulting shape alongside the rearranged entries.

NumPy roll shifts array entries with wraparound while keeping their original shape

A circular shift moves entries through an array and brings the entries that cross one end back at the other end. NumPy roll performs that wraparound rearrangement. Academia Master Trader presents this English lesson for readers in Indonesia. Constructed examples explain positive and negative shifts, matrix axes and the default flattened path, without confusing wraparound with a time lag that introduces empty positions.

Move entries by a stated number of places

After import numpy as np, define a = np.array([2,5,8,11]). The call np.roll(a,1) returns [11,2,5,8]. Each entry moves one position toward a higher index, and eleven wraps from the final position to the first. The four entry shape (4,) is preserved.

The call np.roll(a,2) returns [8,11,2,5]. Two entries wrap around rather than disappearing. No new zero or missing value is inserted. The output contains the original entries in a circularly shifted arrangement, not their arithmetic differences or a new set of measured values.

NumPy roll

A negative shift moves the opposite way

The call np.roll(a,-1) returns [5,8,11,2]. Five moves into the first position, and two wraps from the beginning to the end. The sign of the shift controls the direction of movement; it does not negate the input values.

For this four entry vector, a shift of four returns the same arrangement as the input. A shift of five gives the same arrangement as a shift of one. Circular movement repeats after a complete turn through the selected length. Record the shift and the axis length when explaining equivalent arrangements.

An explicit axis keeps matrix boundaries clear

Define m = np.array([[1,4,7],[2,5,8]]). The call np.roll(m,1,axis=0) returns [[2,5,8],[1,4,7]]. Each row moves one row position, with the final row returning at the beginning. The entries inside each row keep their order.

The call np.roll(m,1,axis=1) returns [[7,1,4],[8,2,5]]. Each row is shifted across its columns, and its last entry returns at the start of that same row. The matrix retains shape (2,3), but the two axis choices describe different rearrangements.

Name the data meaning of each axis before choosing one. A row might represent a category, an observation or something else entirely. Roll does not inspect those meanings and does not automatically move separately stored labels with the numeric entries.

The default uses a flattened path

The call np.roll(m,1) returns [[8,1,4],[7,2,5]]. Without an axis argument, NumPy flattens the array before shifting and restores the original shape afterward. The shape remains (2,3), but entries can cross the old row boundary during the flattened movement.

The final source entry, eight, becomes the first output entry. Seven crosses from the end of the first source row into the beginning of the second output row. This is different from shifting each row independently. An unchanged matrix shape does not prove that its original row groups were kept together.

Wraparound is a choice about the boundary

A circular shift is appropriate only when that boundary behavior matches the intended calculation. If the goal is a previous observation column with an empty first position, roll alone does not supply it. Its first output can contain the final observation, which came from the other end of the sequence.

Keep the transformation distinct from any interpretation of cause, prediction or chronological availability. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the shift, selected axis and wraparound rule so every relocated entry can be traced to its source position.

NumPy flip reverses array positions along selected axes while preserving shape

Reversing an array changes where its entries appear without sorting their numeric values. NumPy flip reverses the order along one or more selected axes and preserves the array shape. Academia Master Trader presents this English lesson for readers in Vietnam. Constructed examples distinguish a reversed vector, a matrix with reversed rows, and a matrix with reversed columns, while explaining why the returned view needs careful handling.

Reverse a vector in its existing order

After import numpy as np, define a = np.array([4,1,9,2]). The call np.flip(a) returns [2,9,1,4]. The final input entry becomes the first output entry, and the first becomes the last. All four entries are retained, so the shape remains (4,).

The output is not sorted from smallest to largest or largest to smallest. Nine stays ahead of one because their positions were reversed together with the rest of the sequence. Flip uses the supplied arrangement as its starting point. If the vector represents observations over time, reversing it also reverses their positional order; it does not change the observation dates themselves.

NumPy flip

Axis zero reverses the row order

Define m = np.array([[1,4,7],[2,5,8]]). The call np.flip(m,axis=0) returns [[2,5,8],[1,4,7]]. The second row now appears first, while the entries within each row retain their original order. The matrix shape stays (2,3).

The values one, four and seven still belong to the same row as one another. The operation changes the row positions, not the column positions inside each row. Keep any corresponding row labels aligned with the same reversal if those labels are stored separately from the numeric matrix.

Axis one reverses entries across each row

The call np.flip(m,axis=1) returns [[7,4,1],[8,5,2]]. Each row remains in its original row position, but the columns appear in the opposite order. The first column becomes the last, and the last becomes the first. Shape (2,3) is preserved again.

For this matrix, axis=-1 refers to the last axis and gives the same result as axis one. A negative axis number is a way to name an axis from the end, not a request to negate the numeric entries. Values retain their signs unless another operation changes them.

The default reverses every axis

The call np.flip(m) returns [[8,5,2],[7,4,1]]. With no axis specified, flip reverses all axes. Here that means reversing both the row order and the column order. It is different from reversing only the rows or only the columns.

The explicit call np.flip(m,axis=(0,1)) gives the same result for this two dimensional matrix. Flip does not exchange the meanings of rows and columns as a transpose would. A two by three matrix stays two by three, even when all of its axes are reversed.

The result is a view of the source

The documentation describes the returned result as a view. With a normal NumPy array, that means the reversed arrangement can share its underlying data with the original rather than holding an independent set of values. The reversal itself does not assign new numbers into m, but later writes through the view can affect the source.

For example, set v = np.flip(m,axis=1). Writing v[0,0] = 99 also changes m[0,2] to ninety nine. Use an explicit copy when an independently editable result is required. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the selected axes, preserved shape and whether later work will edit a shared view or a separate copy.

NumPy tile repeats an array as blocks according to repetition counts by axis

Some array layouts require a whole pattern to appear several times. NumPy tile constructs such a layout by repeating an array as blocks. Academia Master Trader presents this English lesson for readers in Cambodia. Constructed examples explain how repetition counts relate to axes, why a vector can become a matrix, and how block repetition differs from making consecutive copies of each individual entry.

Repeat the complete vector pattern

After import numpy as np, define a = np.array([2,5,8]). The call np.tile(a,2) returns [2,5,8,2,5,8]. The original three entry pattern appears twice in sequence, producing six output entries. The order inside each block stays two, five, eight.

This differs from [2,2,5,5,8,8], where each entry appears twice consecutively. Both arrangements contain two copies of each value, but their positions differ. A later calculation that depends on neighboring values can therefore receive a different arrangement. Choose the intended layout before deciding whether to repeat blocks or individual entries.

NumPy tile

Two repetition counts can create a matrix

The call np.tile(a,(2,1)) returns [[2,5,8],[2,5,8]]. The output has shape (2,3). NumPy treats the vector as shape (1,3) for this two dimensional replication, then repeats that row twice. The second repetition count, one, keeps the three entry pattern once across each row.

The call np.tile(a,(2,2)) returns [[2,5,8,2,5,8],[2,5,8,2,5,8]]. Its shape is (2,6): two rows, each containing two blocks of the vector. The repetition counts are not the requested final shape. They describe how many times the input layout is replicated along each corresponding axis.

A matrix keeps its internal block layout

Define m = np.array([[1,4],[7,9]]). The call np.tile(m,(2,1)) returns [[1,4],[7,9],[1,4],[7,9]]. It stacks two copies of the whole matrix block in the first axis direction. The result has shape (4,2).

Notice the row order: first one and four, then seven and nine, followed by the same two rows again. Tile has not duplicated the first row consecutively before duplicating the second row. The original two row block is the repeated pattern, so its internal row order remains visible in every copy.

A scalar count applies to the last matrix axis

The call np.tile(m,2) returns [[1,4,1,4],[7,9,7,9]]. For a two dimensional input, this single repetition count is treated as (1,2). The first axis is repeated once and the last axis twice, producing shape (2,4).

It does not create a flat vector and does not repeat the matrix twice along every axis. If the desired repetition is in the row direction, write (2,1) explicitly. Supplying one count can be concise, but naming both counts makes the intended matrix layout easier to inspect and explain.

Shape promotion is part of the rule

When the repetition count sequence has more dimensions than the input, NumPy adds leading axes to the input shape. When the input has more dimensions than the count sequence, leading ones are added to the counts. These rules align the shapes before constructing the repeated blocks.

The documentation recommends broadcasting operations rather than tile when broadcasting is the actual purpose. Repeated storage is not automatically necessary merely because an arithmetic operation combines different compatible shapes. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, repetition counts and output shape so each copied block has a clear place in the result.

NumPy repeat duplicates entries consecutively along a selected array axis

Repeating entries changes the arrangement and size of an array without creating new observations. NumPy repeat places copies of each entry consecutively along a selected axis. Academia Master Trader presents this English lesson for readers in Laos. Constructed examples distinguish element repetition, row repetition and a flattened result, so the returned values can be connected to the exact rule that created them.

Repeat each entry before moving on

After import numpy as np, define a = np.array([2,5,8]). The call np.repeat(a,2) returns [2,2,5,5,8,8]. Two appears twice, then five appears twice, then eight appears twice. The count two applies to each input entry, giving six output entries from three source entries.

This is not the arrangement [2,5,8,2,5,8]. That arrangement repeats the whole sequence as a block. Repeat instead places the copies of each entry together before moving to the next entry. State which arrangement is needed before choosing an operation, particularly when both arrangements contain the same collection of values.

NumPy repeat

Counts can differ by position

The call np.repeat(a,[1,3,2]) returns [2,5,5,5,8,8]. The first entry appears once, the second appears three times, and the third appears twice. The count array specifies repetitions associated with input positions, not output values to insert.

A zero count leaves no copies of that entry in the result. For example, np.repeat(a,[1,0,2]) returns [2,8,8]. Five remains in the original a but contributes no output entry in this call. Track the count rule alongside the source if later work must explain why some entries appear more often than others.

No axis means a flat output

Define m = np.array([[1,4],[7,9]]). The default call np.repeat(m,2) returns [1,1,4,4,7,7,9,9]. Without an axis argument, NumPy uses the flattened input and returns a one dimensional array. The original matrix shape (2,2) is not retained in that result.

The values follow the flattened arrangement: one and four from the first row, then seven and nine from the second. Each value is repeated in its turn. A flat output does not, by itself, preserve a separate row boundary. Keep the original shape when those boundaries carry meaning.

An explicit axis repeats rows or columns

The call np.repeat(m,2,axis=0) returns [[1,4],[1,4],[7,9],[7,9]]. It repeats each row consecutively, so the shape changes from (2,2) to (4,2). The columns remain paired within their corresponding rows.

The call np.repeat(m,2,axis=1) returns [[1,1,4,4],[7,7,9,9]]. This repeats the entries along the column direction within each row, producing shape (2,4). Axis zero and axis one therefore create different layouts even when the repetition count is the same.

Counts can also vary along the chosen axis. The call np.repeat(m,[1,2],axis=0) returns [[1,4],[7,9],[7,9]]. The first row appears once and the second twice. Check that the count arrangement fits the selected axis rather than assuming it describes every individual matrix entry.

Copies do not add independent evidence

Repeated values may help construct a required layout, but their presence does not establish additional measurements or independent cases. A longer array can still come entirely from the same small source. Keep the transformation separate from any interpretation of sample size or frequency.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source shape, chosen axis, repetition counts and output shape. Those details explain how the copies were arranged without assigning new meaning to duplicated values.