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 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.

NumPy unique separates distinct values from their frequencies and original positions

A sequence can contain repeated values while having only a few distinct numerical values. NumPy unique identifies those distinct values and can also return counts and positional information. Academia Master Trader explains the function in English for readers in France, using small constructed arrays. The examples distinguish the set of observed values from how often each appears and where the entries occurred in the original sequence.

Begin with distinct values in sorted order

After import numpy as np, define x = np.array([6,2,6,4,2,6]). The call np.unique(x) returns [2,4,6]. The output contains one copy of each distinct value, in sorted order under the default behaviour. Six original entries become three distinct values. The first output is two even though the first input was six.

This is not the same as preserving the first appearance order. Nor is it a calculation of frequency by itself. The plain output tells you which distinct values occur, but it does not tell you that six appears more often than four. Request the additional information needed for the explanation instead of reading it into the values alone.

NumPy unique

Pair each value with its count

The call values, counts = np.unique(x,return_counts=True) returns values [2,4,6] and counts [2,1,3]. The arrays align by output position: two occurs twice, four occurs once and six occurs three times. The counts sum to six, matching the input length.

The figure shows the original sequence and then the distinct values with their aligned counts. A count of three belongs to value six; it is not a third distinct value or a measurement from the original array. Naming both rows avoids confusion between an observed number and the number of times it appears.

First occurrence indices refer back to the input

The call values, first = np.unique(x,return_index=True) returns values [2,4,6] and first indices [1,3,0]. NumPy uses zero based indexing. Two first occurs at index one, four at index three, and six at index zero. The expression x[first] retrieves [2,4,6].

The first indices are aligned with the sorted distinct values, not sorted numerically themselves. Their order therefore need not be increasing. Keeping that distinction explicit helps a reader follow how an output value relates to its earliest appearance in the source sequence.

Inverse indices can reconstruct this sequence

The call values, inverse = np.unique(x,return_inverse=True) returns values [2,4,6] and inverse indices [2,0,2,1,0,2]. Here each inverse entry points into values, not into x. For example, the first inverse entry two selects values at index two, which is six.

The expression values[inverse] reconstructs [6,2,6,4,2,6]. These inverse indices preserve the positional mapping needed for that reconstruction. Counts alone do not preserve the same information. Repeating each distinct value by its count would give the same collection of values grouped together, but not necessarily their original sequence.

Distinguish individual values from whole rows

For a = np.array([[2,5],[2,5],[1,7]]), the call np.unique(a) returns [1,2,5,7] because the default treats the flattened input as individual entries. By contrast, np.unique(a,axis=0) returns [[1,7],[2,5]]. It treats complete rows as the items and keeps one copy of each distinct row.

Those outputs answer different questions. The first lists distinct scalar values anywhere in the matrix. The second lists distinct row patterns. State the axis and the unit being compared before describing a count or calling an entry a duplicate.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record whether the items are values or rows, how the output is ordered and which additional arrays were requested. Then check their alignment. These checks separate distinct values, frequencies and positions without treating any of them as a forecast.

NumPy argsort returns the original positions that arrange values in sorted order

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

Read the returned numbers as positions

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

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

NumPy argsort

Follow the diagram from values to positions

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

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

Keep associated labels aligned

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

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

For matrices, indices belong to the selected axis

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

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

Make ties and flattening explicit

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

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

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

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

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

Begin with an ordinary numerical sequence

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

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

NumPy sort

Keep the source and the returned copy separate

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

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

Sort rows independently with the last axis

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

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

Compare column sorting with flattening

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

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

Treat equal values and numerical types carefully

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

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