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 array split divides uneven lengths into sections that differ by at most one entry

An array does not always divide evenly into the requested number of sections. NumPy provides array split for that situation. With an integer section count, it distributes entries into equal or near equal sections while preserving their sequence along the chosen axis. Academia Master Trader explains this behavior in English for readers in Belarus. Constructed examples show where the longer sections appear and why a requested section count differs from a desired section length.

Eight entries divided into three sections

After import numpy as np, define x = np.array([2,4,6,8,10,12,14,16]). The call parts = np.array_split(x,3) returns [2,4,6], [8,10,12] and [14,16]. These sections have lengths three, three and two. Every input entry appears once in this division, and the original order remains unchanged.

The number three means the number of sections. It is not the maximum length of a section. When designing a workflow that needs a fixed maximum number of entries per section, work out the required section count separately instead of assuming that this argument expresses that limit.

NumPy array split

The remainder goes to the first sections

Let the selected axis have length L and let N be the positive integer number of sections. Integer division gives the base section length. The remainder tells you how many sections need one additional entry. Array split places those longer sections first, followed by the sections with the base length.

For eight entries and three sections, the base length is two and the remainder is two. Therefore, the first two sections contain three entries each and the last contains two. For nine entries divided into four sections, the lengths are three, two, two and two. Section lengths differ by at most one when the integer count form is used.

More sections than entries can produce empty arrays

Consider y = np.array([7,9]). The expression np.array_split(y,4) returns four arrays: [7], [9], [] and []. Two entries cannot populate four nonempty sections. Returning the requested number of sections therefore includes empty arrays in this example.

The base section length is zero and the remainder is two. That produces two sections with one entry and two sections with zero entries. Check section sizes before later operations that expect a nonempty input. Do not interpret an empty section as an extra observed value or insert a made up entry to hide it.

Axis selection also works for matrices

Define m = np.array([[1,2,3,4,5],[6,7,8,9,10]]), with shape (2,5). The call np.array_split(m,3,axis=1) divides the five column positions into widths two, two and one. The results are [[1,2],[6,7]], [[3,4],[8,9]] and [[5],[10]].

Their shapes are (2,2), (2,2) and (2,1). Both rows remain present in each section because the operation divides axis one. Selecting axis zero instead would divide the two row positions. Always calculate section sizes from the selected dimension's length, rather than from the total number of entries in the matrix.

Choose the division rule explicitly

For the eight entry vector, np.split(x,3) raises ValueError because its integer form requires equal division. Array split accepts the same section count and distributes the remainder. The distinction is a rule about section sizes, not a change to the numerical values stored in x.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write the axis length, section count, base length and remainder before dividing. Inspect the output shapes afterward, including any empty sections. A clear division rule keeps the structure of each section explicit without inventing new data.

NumPy split divides an array into sections along a chosen axis

Dividing an array into sections begins with a question about boundaries. Do you want a fixed number of equally sized pieces, or pieces that end at specific positions? NumPy split supports both forms. Academia Master Trader explains the distinction in English for readers in Andorra. The examples use constructed arrays so that section sizes, entry order and axis choices can be checked directly.

An integer specifies the number of sections

After import numpy as np, define x = np.array([2,4,6,8,10,12]). The call parts = np.split(x,3) produces three arrays: [2,4], [6,8] and [10,12]. The integer three asks for three equal sections. It does not ask for sections containing three entries each.

The input length is six, and six divides equally into three sections of length two. The default axis is zero. For this one dimensional array, that axis follows the vector's single dimension. The returned object is a list of arrays, so parts[0] selects the first section and parts[2] selects the third.

NumPy split

A sequence specifies boundary positions

The expression np.split(x,[1,4]) returns [2], [4,6,8] and [10,12]. Positions one and four mark boundaries, using zero based indexing. The corresponding slices are x[:1], x[1:4] and x[4:]. The boundary entry belongs to the next section, rather than to the section that ends there.

Here, the sections have different lengths because explicit positions define the boundaries. Two boundary positions produce three sections. Use a sorted sequence of integer positions when this is the intended form. Before running the operation, write the implied slices to make the boundary interpretation clear, particularly when values happen to resemble their own positions.

Equal sections need equal division

With the six entry vector, np.split(x,4) cannot make four equal sections and raises ValueError. Split does not quietly distribute extra entries among the pieces when its second argument is an integer. The integer form and the boundary sequence form therefore express different requirements, not interchangeable ways of requesting approximate chunk sizes.

NumPy also provides a related function named array split for equal or near equal sections when division is uneven. Choose that behavior deliberately if the task allows section lengths to differ. Do not describe an uneven division as an equal one merely because every input entry appears somewhere in the result.

The chosen axis determines the direction

Define m = np.array([[1,2,3,4],[5,6,7,8]]), which has shape (2,4). The call np.split(m,2,axis=0) returns two arrays with shape (1,4). The first contains the first row, and the second contains the second row. Both retain two dimensions.

With np.split(m,2,axis=1), the results are [[1,2],[5,6]] and [[3,4],[7,8]]. Each has shape (2,2). The operation divides the column dimension while keeping both rows in each section. Axis choice describes a dimension of the input, so check that dimension's length before deciding whether equal division is possible.

Sections can share the original data

The returned sections are views into the original array. They should not be treated as independent copies. For example, after creating parts from x as above, assigning parts[0][0] = 99 also changes the first entry of x to ninety nine. Use a copy of a section when independent storage is required for later changes.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the selected axis, its length and whether the second argument names sections or boundaries. Then inspect the resulting shapes and consider whether shared storage is suitable for the next operation.

NumPy stack joins equal shaped arrays by introducing a new dimension

Combining arrays can preserve each input as a separate slice instead of extending an existing dimension. NumPy stack does this by introducing a new axis. Academia Master Trader explains the operation in English for readers in Vatican City. Small constructed vectors and matrix shapes make the distinction visible. The examples focus on how input order and the position of the new axis determine the output arrangement.

Two vectors can become two rows

After import numpy as np, define x = np.array([2,4,6]) and y = np.array([3,5,7]). Both inputs have shape (3,). The call np.stack((x,y)) returns [[2,4,6],[3,5,7]]. The output has shape (2,3): two input arrays are arranged along a newly created first axis.

The first output row contains x and the second contains y. Within each row, the original entry order is preserved. The default axis is zero, so np.stack((x,y),axis=0) gives the same result. The new dimension identifies which input array supplied the corresponding slice, according to the order in the supplied sequence.

NumPy stack

Put the new dimension at the end

The call np.stack((x,y),axis=1) returns [[2,3],[4,5],[6,7]]. The output shape is (3,2). Each row pairs entries at the same position in the two original vectors. Two is paired with three, four with five and six with seven.

For these one dimensional inputs, axis minus one selects that same final position for the new dimension. Thus np.stack((x,y),axis=-1) gives the same result as axis one. This equality depends on the dimensions of the result. State where the new axis appears instead of assuming that the same axis number has a universal row or column meaning.

Equal shape is a requirement

Every input array in the sequence must have the same shape. A vector with three entries and a vector with two entries do not meet that requirement. Stack does not automatically fill the shorter vector or repeat its entries to make it fit. Decide the intended representation before combining unequal inputs.

Matching total entry counts is also not enough if shapes differ. A matrix with shape (2,3) and one with shape (3,2) both contain six entries, but they are not equal shaped inputs. Write the complete shapes down before stacking, including every dimension length rather than just the total size.

Matrices gain a third dimension

Suppose p and q are two matrices, each with shape (2,3). The expression np.stack((p,q),axis=0) has shape (2,2,3). The new first dimension has length two because there are two input matrices. Each slice selected along that dimension has the original two by three shape.

With axis one, the result has shape (2,2,3) as well, but the new dimension occupies a different position. Equal printed shapes do not guarantee equal arrangements when two dimension lengths happen to match. With axis two, the result has shape (2,3,2), placing the input selection dimension last. Trace a specific entry when dimension lengths alone cannot distinguish the layouts.

A new axis differs from a longer existing axis

For the vector example, np.concatenate((x,y)) returns [2,4,6,3,5,7], a vector with six entries. Stack instead returns a two dimensional result. Both operations preserve the supplied numbers and input order, but they encode the grouping differently in the output shape.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record each input shape, the input sequence and the position of the new axis. Then check that the output has one more dimension than an individual input array. This makes array grouping explicit without turning a new layout into new information.

NumPy concatenate joins arrays along an existing axis with matching other dimensions

Joining arrays requires a rule about where the entries should meet. NumPy concatenate joins a sequence of arrays along an axis that already exists. Academia Master Trader explains the operation in English for readers in San Marino, using small constructed arrays. The examples keep the join direction and shape requirements visible, so the resulting arrangement is clear before any numerical interpretation is made.

Join two vectors in their supplied order

After import numpy as np, define x = np.array([2,5]) and y = np.array([8,11,14]). The call np.concatenate((x,y)) returns [2,5,8,11,14]. The entries from x come first, followed by the entries from y. The output remains one dimensional and has five entries.

The function does not sort, alternate or combine the numbers arithmetically. Reversing the input sequence to np.concatenate((y,x)) returns [8,11,14,2,5]. Input order is therefore part of the result. Write down that order when explaining the join rather than describing the output as an unordered collection.

NumPy concatenate

Join rows along the first axis

Define a = np.array([[1,3],[5,7]]) and b = np.array([[9,11]]). The call np.concatenate((a,b),axis=0) returns [[1,3],[5,7],[9,11]]. The first array has two rows, the second has one, and both have two columns. The result has three rows and two columns.

The row counts can differ because axis zero is the dimension being joined. The column counts must match in this example. Each complete row from b can then follow the rows from a without leaving an undefined position in the rectangular output. The default axis is zero, so omitting the axis gives the same result here.

Join columns when the row counts match

Define c = np.array([[9],[11]]). The call np.concatenate((a,c),axis=1) returns [[1,3,9],[5,7,11]]. Both inputs have two rows. The first has two columns and the second has one, giving an output with two rows and three columns.

Although b and c contain the same two numerical values, their shapes are different. The one row shape of b suits the earlier vertical join, while the one column shape of c suits this horizontal join. Values alone do not determine compatibility. Check each input's number of dimensions and the lengths outside the selected join axis.

Flatten explicitly with axis None

The call np.concatenate((a,b),axis=None) returns [1,3,5,7,9,11]. With axis None, the input arrays are flattened before being joined. The output is a single vector rather than a matrix with three rows.

This setting can be useful when only the sequential entries are needed, but it removes the row grouping from the output shape. State that transformation rather than calling it the same join in another notation. A flattened vector and a three by two matrix have different shapes even when their entries appear in corresponding order.

Existing and new axes are different choices

Concatenate extends an existing axis; it does not create a new one to identify each input array. For the vector example, the two inputs become a longer vector. Their original boundary is not stored as a separate dimension in the result. If that boundary matters later, record the input lengths or choose an operation designed to introduce a new axis.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input sequence, every input shape and the selected axis. Then check that the other dimensions match and that the joined dimension has the expected combined length. These checks make the arrangement explicit without assigning extra meaning to the joined values.

NumPy rot90 turns an array through quarter turns within a specified plane

An array rotation changes where entries appear in a grid. NumPy rot90 performs quarter turns in a plane defined by two axes. Academia Master Trader explains this operation in English for readers in Monaco, using a small rectangular matrix. The examples distinguish rotation from sorting, numerical calculation and a simple row exchange. Following the corners makes the direction visible and helps explain why a rectangular array can change its shape.

Read the original matrix before turning it

After import numpy as np, define a = np.array([[1,2,3],[4,5,6]]). It has two rows and three columns. The top row is one, two, three, and the bottom row is four, five, six. Its four corners are one, three, four and six.

The call np.rot90(a) returns [[3,6],[2,5],[1,4]]. With the default settings, a two dimensional matrix turns counterclockwise by ninety degrees. Three becomes the top left entry, six becomes the top right entry and one becomes the bottom left entry. The result has three rows and two columns.

NumPy rot90

Count quarter turns with k

The parameter k is the number of quarter turns. The call np.rot90(a,k=2) returns [[6,5,4],[3,2,1]]. Two quarter turns give a half turn, returning the shape to two rows by three columns. Both the row order and the entry order within each row are reversed in this two dimensional example.

The call np.rot90(a,k=4) restores the original arrangement. Four quarter turns complete a full turn. These comparisons make k easier to interpret than a general phrase such as rotating repeatedly. The parameter counts ninety degree steps, not individual positions within a row or column.

A negative count turns in the opposite direction

The call np.rot90(a,k=-1) returns [[4,1],[5,2],[6,3]]. Under the default axis order, this is a clockwise quarter turn. Four moves to the top left corner and three moves to the bottom right corner. The output again has three rows and two columns.

A positive quarter turn and a negative quarter turn therefore have the same output shape but different arrangements. Shape alone does not establish direction. Trace a named corner from the input to the output, then check a second corner to confirm which way the matrix turned.

Axis order defines the orientation of the plane

The default axes are (0,1). The call np.rot90(a,k=1,axes=(1,0)) produces the same arrangement as np.rot90(a,k=-1,axes=(0,1)). Reversing the order of the two axes reverses the rotation direction for the same positive count.

The two axes must be different, and the input must have at least two dimensions. For an array with more than two dimensions, the axes specify the plane in which the turn occurs. Write both axes in order when describing such an operation. Naming only the two dimensions without their order leaves the direction unclear.

A rotated view is not necessarily an independent copy

NumPy describes the result as a rotated view. For a NumPy array, that means the output can refer to the original entries rather than storing an independent collection of values. If later work requires a separate array, request a copy explicitly, such as np.rot90(a).copy().

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, ordered axis pair and quarter turn count. Then trace the corners and check the resulting shape. A rotation rearranges the supplied entries; it does not generate additional measurements or make a numerical pattern more predictive.

NumPy flip reverses entry order along chosen axes while preserving array shape

Reversing an array changes positional order without sorting its values or changing its dimensions. NumPy flip performs that reversal along one axis, several selected axes or every axis by default. Academia Master Trader explains the operation in English for readers in Liechtenstein. Small constructed examples show exactly what moves, including how a reversed view relates to the original array. Position changes should be described separately from any interpretation of the numbers.

A vector reverses from end to beginning

After import numpy as np, define x = np.array([3,8,2,6]). The call np.flip(x) returns [6,2,8,3]. Six moves from the last position to the first, two moves to the second, eight moves to the third and three moves to the last. The array still has four entries.

The output is neither ascending nor descending numerical order. Flip reverses positions, regardless of the magnitudes stored there. Calling it a sorting operation would therefore describe a different rule. Trace the original indices from last to first to explain why the output begins with six rather than the smallest or largest value.

NumPy flip

Choose the axis when reversing a matrix

Define a = np.array([[1,4,7],[2,5,8]]). The call np.flip(a,axis=0) returns [[2,5,8],[1,4,7]]. It reverses the order of rows. The entries inside each row retain their horizontal order, so the row beginning with two remains two, five, eight.

The call np.flip(a,axis=1) returns [[7,4,1],[8,5,2]]. It reverses the positions within each row instead. The first row remains the first row, but its entries run in the opposite direction. Both outputs keep the original shape of two rows and three columns. The selected axis determines which positions exchange places.

The default reverses every axis

For the same matrix, np.flip(a) returns [[8,5,2],[7,4,1]]. Both the row order and the order within each row are reversed. In this two dimensional case, the result matches np.flip(a,axis=(0,1)).

This default is different from reversing only the rows. Write the axis choice explicitly in an explanation when a reader might otherwise assume a vertical reversal. A tuple names the axes to reverse together; it does not describe a sequence of new dimensions. Flip preserves the dimension lengths while changing their positional directions.

Negative axes count from the final dimension

For this matrix, np.flip(a,axis=-1) gives the same output as np.flip(a,axis=1). The negative index minus one selects the final axis. For a matrix, that is the column direction. The meaning depends on the number of dimensions in the input, rather than on a fixed physical direction for every possible array.

This notation can be useful when the final dimension has a consistent role across inputs with different numbers of dimensions. Record what that dimension represents before using a negative axis. The numerical output can be correct while a description of its rows, columns or other dimensions is incomplete.

A reversed view can share the original storage

For a NumPy array, flip returns a view rather than an independent copy of the entries. To make the consequence visible, start with a fresh b = np.array([1,2,3]) and set r = np.flip(b). Assigning r[0] = 9 changes b to [1,2,9], because the first entry of r refers to the final entry of b.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, selected axes and whether an independent copy is needed. Then trace the first and last positions along each reversed axis. This separates ordering, shape and shared storage when explaining an array transformation.

NumPy roll moves entries cyclically and brings boundary values back into the array

Moving array entries can mean either discarding boundary values or wrapping them around. NumPy roll uses the second interpretation: entries that pass one boundary return at the other. Academia Master Trader explains this cyclic operation in English for readers in the Netherlands. Small constructed examples show how the shift direction and selected axis determine the output, without treating a rearranged sequence as a new collection of observations.

A positive shift moves entries toward higher positions

After import numpy as np, define x = np.array([2,5,8,11]). The call np.roll(x,1) returns [11,2,5,8]. Two moves from index zero to index one, five moves to index two and eight moves to index three. Eleven wraps from the final position back to index zero.

No entry is removed and no empty position is created. The array still contains four values. This makes roll different from an operation that inserts a blank or a missing value at the beginning. The boundary behaviour is part of the operation, not an optional interpretation to choose after seeing the output.

NumPy roll

A negative shift reverses the direction

The call np.roll(x,-1) returns [5,8,11,2]. Five moves to index zero, while two wraps to the final position. A shift of two returns [8,11,2,5]. The sign sets the direction and the magnitude sets how many positions each entry moves.

A shift equal to this vector's length restores its original arrangement. Thus np.roll(x,4) returns [2,5,8,11]. A shift of five has the same result as a shift of one. These comparisons help explain that a cyclic shift follows a repeating positional cycle rather than continually extending the array.

The default handles a matrix through its flattened order

Define a = np.array([[1,2,3],[4,5,6]]). The call np.roll(a,1) returns [[6,1,2],[3,4,5]]. By default, NumPy flattens the input before rolling and then restores the original shape. The result therefore still has two rows and three columns.

Six returns to the first position of the flattened sequence, and three crosses from the end of the original first row into the beginning of the second row. This is not the same as shifting each row independently. State whether an axis was supplied before describing how the matrix boundaries behave.

An explicit axis defines separate cyclic paths

The call np.roll(a,1,axis=1) returns [[3,1,2],[6,4,5]]. Each row rolls horizontally within itself. Three wraps to the first position of its row, while six does the same in the second row. Values do not cross between rows in this example.

The call np.roll(a,1,axis=0) returns [[4,5,6],[1,2,3]]. Complete rows exchange vertical positions because there are only two rows. The output shape remains two by three in both cases. Shape alone therefore cannot tell you which path each value followed; the axis is needed as well.

Explain wrapped entries before using the result

For a time ordered record, a cyclic shift places a value from one end next to values from the other. That can suit a deliberately periodic construction, but it is not a blank filled lag. The wrapped entry remains a real number from the input and should be identified as such when explaining the rearrangement.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, shift and axis, then trace one interior entry and one boundary entry. Check that the output keeps the original shape and that every wrapped value goes where the cyclic rule requires. This keeps positional rearrangement distinct from adding or predicting data.

NumPy tile repeats a complete array pattern along specified dimensions

A repeating numerical pattern can be represented by joining copies of a small array. NumPy tile performs that construction using a repetition count for each relevant dimension. Academia Master Trader explains the operation in English for readers in Portugal. The examples use invented arrays to make block order and output shape visible. Repeating an existing pattern creates copies of the supplied numbers, not additional observations or new evidence about a sequence.

Repeat the complete vector as a block

After import numpy as np, define x = np.array([2,5,9]). The call np.tile(x,2) returns [2,5,9,2,5,9]. One complete copy of the vector follows another. The order inside each copy remains two, five, nine. The output has six entries because the original three entry block appears twice.

This differs from repeating each entry consecutively. The tiled output is not [2,2,5,5,9,9]. The unit being copied is the complete input pattern. State that unit before describing the result, especially when the values could be interpreted as an ordered record. Pattern repetition does not add a calculation between one copy and the next.

NumPy tile

A pair of counts can produce a matrix

The call np.tile(x,(2,2)) returns [[2,5,9,2,5,9],[2,5,9,2,5,9]]. There are two rows, and each row contains two copies of x. The shape is two by six. The first repetition count controls the vertical dimension and the second controls the horizontal dimension in this two dimensional example.

The input vector originally had one dimension. To use two repetition dimensions, NumPy treats it as having shape one by three before constructing the output. That added leading dimension explains why the first count creates rows instead of repeating each scalar entry individually. Shape reasoning is more reliable than guessing from the flattened numbers alone.

Follow an existing matrix through both axes

Define a = np.array([[1,3],[6,8]]). The call np.tile(a,(2,1)) returns [[1,3],[6,8],[1,3],[6,8]]. It places two copies of the complete two row block vertically. The original row order is preserved inside each copy, giving four rows and two columns.

The call np.tile(a,(1,2)) instead returns [[1,3,1,3],[6,8,6,8]]. It joins two copies horizontally, giving two rows and four columns. The pair of counts determines which dimension grows. Both arrays have eight entries, yet their shapes describe different arrangements and lead to different positional interpretations.

Short repetition specifications align from the end

For that same matrix, np.tile(a,2) gives the same result as np.tile(a,(1,2)). Because a already has two dimensions, the single repetition count is treated as a horizontal count with a leading one. It does not flatten the matrix before repeating it.

More generally, NumPy adds leading ones to a short repetition specification until it matches the number of input dimensions. Conversely, when the repetition specification has more dimensions than the input, leading dimensions are added to the input shape. Write these leading ones down when explaining a shape change so that the alignment is explicit.

Check the shape as well as the values

For a matrix with shape two by two and repetition counts (3,2), the tiled output has shape six by four. Each corresponding dimension is multiplied by its repetition count. This gives a compact check before reading every output entry. It also shows how quickly a constructed output can grow when several dimensions are repeated.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, complete block and repetition counts. Then verify the resulting shape and the order inside each copy. This keeps array construction separate from any claim that a repeated pattern predicts what comes next.

NumPy repeat expands individual entries according to explicit repetition counts

Repeating a value changes how an array represents a sequence without creating new observations. NumPy repeat provides a direct way to make consecutive copies of individual entries or selected rows and columns. Academia Master Trader explains this operation in English for readers in Spain. Small constructed arrays make the order visible, so the repeated output can be traced back to its source rather than mistaken for additional independent information.

Begin with consecutive copies of each entry

After import numpy as np, define x = np.array([3,7,2]). The call np.repeat(x,2) returns [3,3,7,7,2,2]. Each original entry is written twice before the operation moves to the next entry. The first pair comes from three, the second pair from seven and the third pair from two.

This is different from repeating the complete sequence as a block. The result is not [3,7,2,3,7,2]. The distinction matters whenever order carries meaning. Describe whether the operation repeats each entry or an entire pattern before interpreting the expanded array. Here the repeated neighbours share the same source entry.

NumPy repeat

Give different entries different counts

The call np.repeat(x,[1,3,2]) returns [3,7,7,7,2,2]. The first count one belongs to three, the second count three belongs to seven and the third count two belongs to two. The count vector aligns with the input positions, not with the numerical magnitudes of the values.

The output length is six because the counts sum to six. A repetition count of one keeps one copy; it does not add one extra copy to an automatically retained original. A count of zero contributes no entries. For example, np.repeat(x,[1,0,2]) returns [3,2,2]. This makes the meaning of each count explicit.

The default flattens a matrix

Define a = np.array([[1,4],[6,8]]). Without an axis, np.repeat(a,2) returns [1,1,4,4,6,6,8,8]. The matrix entries are taken in flattened order, then each is repeated twice. The output is one dimensional, even though the input had two dimensions.

The original row grouping is therefore not retained in the output shape. When writing an explanation or a calculation, record that shape change alongside the values. An eight entry vector and a matrix containing eight entries may hold related numbers while supporting different later operations.

An axis keeps the other dimensions intact

For the same matrix, np.repeat(a,2,axis=0) returns [[1,4],[1,4],[6,8],[6,8]]. The first row is repeated twice, then the second row is repeated twice. The output shape is four rows by two columns. The column count stays unchanged.

By contrast, np.repeat(a,2,axis=1) returns [[1,1,4,4],[6,6,8,8]]. Each column position is repeated along the horizontal axis, giving two rows by four columns. Both outputs contain eight entries, but their shapes and groupings differ. Naming only the total number of entries would leave out that distinction.

Check counts against the selected axis

The call np.repeat(a,[1,2],axis=0) returns [[1,4],[6,8],[6,8]]. The two counts correspond to the two input rows. The first row contributes once and the second contributes twice. With an explicit axis, interpret a count vector against positions on that axis rather than against every scalar entry in the matrix.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write down the input shape, repetition counts and axis before tracing the result. Then check the output shape and entry order. Repeated entries are copies defined by the operation, not evidence that the underlying event happened more often.

NumPy bincount uses each nonnegative integer as an output position for counting

An array of small integer codes can describe repeated categories. NumPy bincount turns those codes into counts by using each code as a position in the output array. Academia Master Trader explains the function in English for readers in Italy, with constructed numerical examples. The important distinction is between the input position, the category code stored there and the output position that receives the count.

Read output positions as category labels

After import numpy as np, define x = np.array([0,2,2,4,2,0]). The call np.bincount(x) returns [2,0,3,0,1]. Output position zero contains two because zero appears twice in x. Output position two contains three because two appears three times. Output position four contains one because four appears once.

The zeros at output positions one and three are meaningful. They show that those codes do not occur in the input. NumPy has not removed those positions to produce a compact list of observed categories. The category labels are implicit in the array indices, so retaining the empty positions keeps every count attached to the correct code.

NumPy bincount

Check the length and the count total

For this nonempty input, the largest code is four and the default output has five positions, indexed zero through four. The counts sum to six, matching the input length. These are two different checks: the output length reflects the largest code, while the count total reflects the number of entries.

The figure pairs every output position with its count, including the empty categories. Reading the two rows together gives code zero with count two, code one with count zero, code two with count three, code three with count zero and code four with count one. The position of a number is part of its meaning.

Minimum length extends the available positions

The call np.bincount(x,minlength=7) returns [2,0,3,0,1,0,0]. The last two positions make codes five and six explicit, even though neither code appears in x. This can keep category arrays the same length when different groups contain different subsets of a known code range.

Minimum length is a lower bound, not an upper bound. If the input includes code eight, an output with positions through eight is needed even when minlength is seven. Decide the intended code range before allocating or comparing outputs. Widely separated integer labels can produce a long output even when the input itself is short.

Weights replace counts with sums

Define w = np.array([1,5,2,7,3,4]). The call np.bincount(x,weights=w) returns [5.,0.,10.,0.,7.]. The two entries with code zero contribute weights one and four, giving five. The three entries with code two contribute five, two and three, giving ten. Code four receives weight seven.

The weights align with input positions, not with the final output categories. There are six weights for six input entries. Each code directs its corresponding weight into the appropriate output position. Once weights are supplied, describe the result as a sum of weights for each code rather than a frequency count.

Keep the input contract explicit

The input must be one dimensional and contain nonnegative integers. Negative codes, a matrix supplied directly or floating point input do not meet that contract. Even floating point entries written as whole numbers still have a floating point type. Establish the intended categories and their integer representation before using the function.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Write down the code range, whether weights are present and the required minimum output length. Then explain the output by its positions. This approach keeps category labels, counts and weighted sums distinct when preparing a numerical summary.