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 unpackbits expands unsigned bytes into explicit zero and one entries

A stored byte can represent eight logical positions rather than one ordinary measurement. NumPy unpackbits exposes those positions as an array containing zeros and ones. Academia Master Trader presents this English lesson for readers in Cabo Verde, using constructed unsigned bytes to explain bit order, output length and unpacking along a chosen axis.

The input dtype identifies unsigned bytes

After import numpy as np, define stored = np.array([13],dtype=np.uint8). The call np.unpackbits(stored) returns [0,0,0,0,1,1,0,1].

The output entries have dtype uint8, but each entry is now either zero or one. A single input byte has expanded into eight output entries.

Under the default big bit order, those positions correspond to weights 128, 64, 32, 16, 8, 4, 2 and 1. The active weights eight, four and one add to thirteen.

Use the required unsigned eight-bit input type. An array of arbitrary integers is not the same representation, even when its displayed numbers look small enough to fit in a byte.

Unsigned byte expanded into eight bits

Bit order controls which position comes first

The call np.unpackbits(stored,bitorder='little') returns [1,0,1,1,0,0,0,0]. The least significant position appears first rather than last.

Both sequences describe the same stored byte under different position conventions. The choice does not change thirteen into a different input value or sort the resulting bits.

Match bit order to the convention used by the producer of the packed data. A sequence containing the expected number of entries can still be interpreted incorrectly when significance runs in the wrong direction.

Count controls how much output is retained

For packed = np.array([160],dtype=np.uint8), the default output is [1,0,1,0,0,0,0,0]. The call np.unpackbits(packed,count=3) instead returns [1,0,1].

This is useful when only three logical entries were originally packed and trailing zeros merely completed the byte. The original length must come from retained metadata; the byte does not mark which zeros were padding.

A negative count removes positions from the end. Here count=-5 also leaves [1,0,1]. A positive count of ten produces the eight available bits followed by two extra zeros.

Those added zeros are output padding, not newly recovered source information. Count controls length rather than discovering how many meaningful entries the producer intended.

Axis determines which dimension expands

Define rows = np.array([[128],[1]],dtype=np.uint8). The call np.unpackbits(rows,axis=1) returns two rows of eight entries, with shape (2,8).

The first row starts with one followed by seven zeros. The second starts with seven zeros followed by one. Each input row remains separate while its byte dimension expands.

With axis omitted, the same two input bytes produce one flat array of sixteen entries. Record the intended output grouping instead of assuming that unpacking preserves every original dimension automatically.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the byte dtype, bit order, original logical length and unpacking axis together when reading packed data.

NumPy packbits stores logical entries as bits in unsigned bytes

A sequence of logical entries can occupy one bit per entry when packed into bytes. NumPy packbits performs this conversion, returning unsigned eight-bit integers. Academia Master Trader presents this English lesson for readers in São Tomé and Príncipe, using constructed sequences to explain bit order, padding and the difference between logical packing and preserving arbitrary integer values.

Eight logical entries fill one byte

After import numpy as np, define bits = np.array([1,0,1,0,0,0,0,1],dtype=np.uint8). The call np.packbits(bits) returns [161], with output dtype uint8.

The default bit order is big. Reading the sequence from left to right assigns weights of 128, 64, 32, 16, 8, 4, 2 and 1. The active positions contribute 128 plus 32 plus 1, producing 161.

The output integer represents eight logical positions. It is not their sum, their average or an encoded text character chosen by the function.

Eight logical positions packed into one byte

Bit order changes the weights

The call np.packbits(bits,bitorder='little') returns [133]. The same logical entries now receive weights starting with one and increasing toward 128.

The active positions contribute 1 plus 4 plus 128, producing 133. The input sequence has not been reversed in place. The rule assigning significance within each output byte has changed.

Bit order is not an axis selection or a choice of row-major versus column-major traversal. Record it separately when a later operation must interpret the stored byte.

Short groups are padded with zero bits

For short = np.array([1,0,1],dtype=np.uint8), the call np.packbits(short) returns [160]. Under big bit order, the three entries occupy the first three bit positions; five trailing zero bits complete the byte.

The original length is therefore useful metadata. The packed byte alone does not distinguish three entries followed by padding from eight meaningful entries ending in five zeros.

Padding happens at the end of each packed sequence. It does not indicate that the source contained extra observations or that missing values were estimated.

An explicit axis keeps other dimensions separate

Define rows = np.array([[1,0,1],[0,1,0]],dtype=np.uint8). The call np.packbits(rows,axis=1) returns [[160],[64]], with shape (2,1). Each row is packed separately and receives its own trailing padding.

With the axis omitted, np.packbits(rows) returns [168]. The input is flattened into six logical positions before a single byte is formed, so its grouping differs from the row-wise result.

Input entries are interpreted logically: zero becomes a zero bit, and a nonzero integer becomes a one bit. For example, np.packbits([0,2,0,-3]) returns [80]. This operation does not preserve the original magnitudes two and minus three.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the original shape, sequence length, packing axis and bit order alongside packed logical data.

NumPy ravel multi index converts coordinates into flat positions with explicit boundary rules

A grid coordinate and a flat position can describe the same location, but only when shape and traversal order agree. NumPy ravel multi index calculates that flat position from coordinates. Academia Master Trader presents this English lesson for readers in Guinea-Bissau, using a constructed grid to explain row-major order, column-major order and boundary handling.

Coordinates need the shape that gives them meaning

After import numpy as np, consider a grid with shape (3,4): three rows and four columns. The call np.ravel_multi_index((2,1),(3,4)) returns nine.

Coordinates are zero-based. In default C order, reaching row two passes two complete rows of four positions. Column one adds one more position, giving the flat index nine.

The function receives coordinates and dimensions, not an array of stored observations. It does not search for a value or change the grid. Its result describes a position under the supplied convention.

Grid coordinates to flat position

Traversal order changes the position number

The call np.ravel_multi_index((2,1),(3,4),order='F') returns five. Under column-major order, column one follows one complete column of three positions, then row two adds two positions.

Both nine and five can describe coordinates (2,1), but they belong to different flattening conventions. Neither convention changes the coordinate pair or creates a new grid value.

When passing a flat index between operations, carry its dimensions and order as well. A position number without those details is not a complete description of its multidimensional location.

Coordinate arrays are organized by axis

The call np.ravel_multi_index(([0,1,2],[0,1,3]),(3,4)) returns [0,5,11].

The first sequence supplies row coordinates, and the second supplies column coordinates. Corresponding positions pair into (0,0), (1,1) and (2,3).

Do not read the outer tuple as a list of complete coordinate pairs. Each member describes one axis. With more dimensions, supply the corresponding additional coordinate arrays and dimension lengths.

Boundary handling is a deliberate choice

The default boundary mode is mode='raise'. Coordinates outside the supplied dimensions cause an error instead of silently selecting another position.

For shape (3,4), row three lies beyond the final valid row, which is row two. The call np.ravel_multi_index((3,-1),(3,4),mode='wrap') returns three: row three wraps to row zero, while column minus one wraps to column three.

With mode='clip', the same coordinates return eight. The row clips to two, and the negative column clips to zero. Clipping a negative coordinate therefore differs from ordinary negative indexing, which often refers to positions counted from the end.

Choose a boundary mode because it matches the intended interpretation, not merely because it produces an index. Wrapping and clipping can yield valid positions that describe different locations.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record coordinates, dimensions, traversal order and boundary mode when converting a location into a flat index.

NumPy unravel index converts flat positions into coordinates for a chosen shape

A single position number can identify an entry in a flattened array, while a multidimensional array needs one coordinate per axis. NumPy unravel index connects those descriptions. Academia Master Trader presents this English lesson for readers in Senegal, using a constructed grid to explain shape, traversal order and the structure of returned coordinates.

Start with a shape and a flat position

After import numpy as np, define grid = np.arange(12).reshape(3,4). The grid has three rows and four columns. Its rows contain [0,1,2,3], [4,5,6,7] and [8,9,10,11].

The call np.unravel_index(9,grid.shape) returns (2,1). These are zero-based coordinates: row two and column one. The expression grid[2,1] returns nine.

In this deliberately numbered grid, the value happens to equal its flat position. The function does not inspect stored values or search for a matching entry. It calculates coordinates from the supplied position and shape.

Flat position to grid coordinates

C order moves through the final axis first

The default order is order='C'. In a two-dimensional grid, this means moving across a row before advancing to the next row.

For shape (3,4), flat position nine covers two complete rows of four entries, followed by one additional column position. The resulting coordinates are therefore (2,1).

Changing the supplied shape changes the interpretation. The call np.unravel_index(9,(4,3)) returns (3,0): three complete rows of three entries, with no additional column movement.

Both shapes contain twelve positions. Equal total size does not make their coordinates interchangeable. Keep the shape beside the flat position whenever coordinates will be used later.

F order follows a different traversal

The call np.unravel_index(9,(3,4),order='F') returns (0,3). Column-major traversal advances along the first axis before moving to the next column.

This argument describes how the flat index is interpreted. It does not rotate a grid, transpose values or change an existing array's shape.

An index produced under one traversal order must be interpreted under that same order. A valid coordinate pair can still point to the wrong intended entry if the flattening convention is mismatched.

Several positions return one array per axis

The call np.unravel_index([0,5,11],(3,4)) returns row coordinates [0,1,2] and column coordinates [0,1,3].

The returned tuple is organized by axis, not by entry. Pair corresponding positions to obtain (0,0), (1,1) and (2,3). Each coordinate array retains the shape of the supplied index array.

For this twelve-position grid, valid flat indices run from zero through eleven. A flat index of twelve is outside the supplied shape, rather than the first position of a new row.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape, zero-based index and traversal order before interpreting a flat position as coordinates.

NumPy roll shifts entries cyclically while retaining the original array shape

A cyclic rearrangement can move entries without creating or removing a position. NumPy roll returns shifted entries, wrapping any value crossing an end back to the other side. Academia Master Trader presents this English lesson for readers in Côte d'Ivoire, focusing on repeated circuits, reversing a shift and applying one shift amount across several axes.

A short vector reveals the boundary rule

After import numpy as np, define x = np.array([2,4,6,8]). The call np.roll(x,1) returns [8,2,4,6]. The final entry wraps to the first position, and the remaining entries advance toward larger indices.

Shape stays (4,). There is no blank opening position. This boundary rule is suitable only when the end and beginning should connect conceptually.

NumPy roll cyclic shift example

Large shifts can describe the same arrangement

For this four-entry vector, np.roll(x,9) gives the same ordering as a shift of one: [8,2,4,6]. Nine positions contain two full circuits and one additional position.

The call np.roll(x,8) returns [2,4,6,8], matching the original ordering. Eight positions cover two complete circuits of length four.

The relevant circuit length belongs to the selected axis. A shift amount alone cannot identify whether an output changes: the same amount can be a full circuit on one axis but only part of a circuit on another.

This is a statement about ordering, not a claim that NumPy returns the original Python object when the arrangement repeats.

An opposite shift restores positions

Set shifted = np.roll(x,3). Its entries are [4,6,8,2]. Applying np.roll(shifted,-3) returns [2,4,6,8].

The inverse works because the second operation uses the opposite shift on the same axis. Using another axis in a multidimensional array would describe a different movement, rather than undoing the first one.

A cyclic shift does not estimate new observations. Reversing it restores positions because the operation rearranged existing entries, not because it reconstructed missing information.

One amount can apply across multiple axes

Define grid = np.arange(12).reshape(3,4). Its rows are [0,1,2,3], [4,5,6,7] and [8,9,10,11].

The call np.roll(grid,1,axis=(0,1)) applies the same shift of one to both directions. Its rows become [11,8,9,10], [3,0,1,2] and [7,4,5,6]. Shape remains (3,4).

Here the scalar shift is shared by the listed axes. A tuple of shift amounts instead pairs each amount with its corresponding axis. Keep those two forms distinct when reading code.

For this two-dimensional grid, axis=-1 identifies the final axis, equivalent to axis=1. Omitting axis is different: NumPy shifts a flattened sequence and then restores shape, rather than independently cycling the final direction.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the axis length, shift amount and boundary meaning when explaining a cyclic rearrangement.

NumPy rollaxis relocates one axis using a start boundary rather than a value shift

Older array-processing code may use NumPy rollaxis to change axis order. The operation relocates one axis while keeping the remaining axes in their relative order. Academia Master Trader presents this English lesson for readers in Guinea, using a constructed array to explain the start argument and distinguish axis relocation from rolling numerical entries.

The default brings the chosen axis to the front

After import numpy as np, define x = np.arange(24).reshape(2,3,4). Its shape is (2,3,4). The call front = np.rollaxis(x,2) produces shape (4,2,3).

The original axis two becomes the first axis. The original length-two and length-three axes keep their relative order behind it. All 24 numerical entries remain present.

For a concrete coordinate, x[1,2,3] equals 23. The corresponding entry in the relocated view is front[3,1,2], also 23. The coordinate components follow their axes to the new positions.

This is a structural change. It does not sort the entries or move each value a fixed number of positions within an axis.

NumPy rollaxis uses a start boundary

The start argument needs careful interpretation

When start is less than or equal to the chosen axis, the selected axis moves to that start position. For example, np.rollaxis(x,2,1) produces shape (2,4,3).

When start is greater than the chosen axis, the selected axis moves before that boundary in the original axis order. For this three-dimensional input, np.rollaxis(x,0,3) produces shape (3,4,2).

The latter call moves the original first axis to the end. Start three identifies the boundary after the existing axes; it does not create an output axis numbered three.

Avoid reading start as an ordinary final destination in every case. Its boundary meaning explains why moving an earlier axis forward can produce a different final index from the numeric start value.

Rollaxis and roll answer different questions

Rollaxis changes axis order. NumPy roll, by contrast, shifts numerical entries along an axis and brings entries that pass one end back at the other end.

Those operations can have very different meanings even when a printed array looks similar. Record whether the task calls for rearranging coordinate directions or cycling values within a direction.

Axis relocation also differs from a general reshape. The existing axes keep their individual lengths and coordinate meanings as their positions change.

Prefer moveaxis for new code

NumPy continues to support rollaxis for backward compatibility, but its documentation recommends moveaxis. For this input, np.moveaxis(x,0,-1) gives the same axis arrangement as np.rollaxis(x,0,3).

Current NumPy returns a view from rollaxis. A different arrangement therefore does not imply separate editable storage. Make an explicit copy if later edits must remain independent of the source.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the selected axis, start boundary and final axis order when reading older rollaxis code.

NumPy transpose specifies an output axis order rather than a new set of values

A familiar matrix transpose exchanges rows and columns. For an array with more axes, NumPy transpose describes a more general permutation of axis order. Academia Master Trader presents this English lesson for readers in Niger, using constructed examples to explain the default reversal, explicit permutations and the special case of a one-dimensional vector.

The default reverses the axis order

After import numpy as np, define x = np.arange(24).reshape(2,3,4). Its shape is (2,3,4). The call np.transpose(x) produces shape (4,3,2).

Without an explicit axes argument, transpose reverses the order of all axes. It does not reverse the numerical sequence within each original axis as a separate value operation.

For a source entry, x[1,2,3] equals 23. In the default transposed result, that entry is addressed at coordinate [3,2,1]. The coordinates follow the reversed axis order.

The total number of elements remains 24. No summation, averaging or selection of entries is part of this permutation.

NumPy transpose explicit output axis order

An explicit permutation names input axes in output order

The call turned = np.transpose(x,(1,2,0)) produces shape (3,4,2). Output axis zero corresponds to input axis one, output axis one corresponds to input axis two, and output axis two corresponds to input axis zero.

Read the tuple as an ordered list of input axes, not as destination positions paired with those axes. This interpretation differs from a source-and-destination interface.

For the same entry used above, turned[2,3,1] equals 23. The input coordinate components have been rearranged in the order specified by (1,2,0).

A valid permutation includes every input axis exactly once. Repeating an axis or omitting one does not describe a complete transpose of that array.

A matrix and a vector behave differently

For matrix = np.array([[1,2,3],[4,5,6]]), transposition changes shape (2,3) to (3,2). Its first output row is [1,4], formed by the first column of the input.

For vector = np.array([2,5,8]), however, np.transpose(vector) still has shape (3,). Reversing an order containing only one axis leaves that order unchanged.

A transpose alone does not turn a one-dimensional vector into a two-dimensional column. Add the intended second axis explicitly when the required output shape is (3,1).

Inverting a permutation is an axis-order decision

The permutation (1,2,0) can be reversed by applying (2,0,1) to its result. In this example, np.transpose(turned,(2,0,1)) restores the original axis order and shape.

NumPy returns a view whenever possible. A changed arrangement is therefore not a promise of independent editable data. Use an explicit copy when later edits must remain separate from the source.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input axis order, output permutation and one corresponding coordinate before relying on a transpose.

NumPy swapaxes exchanges two axis positions without sorting the stored values

Array shape describes the lengths of axes in a particular order. NumPy swapaxes exchanges two of those axis positions. Academia Master Trader presents this English lesson for readers in Mali, using a constructed array to show how coordinates follow the exchange and why equal axis lengths can hide a structural change.

Exchange the first and final axes

After import numpy as np, define x = np.arange(24).reshape(2,3,4). Its shape is (2,3,4), and the call swapped = np.swapaxes(x,0,2) produces shape (4,3,2).

The original first axis becomes the final axis, while the original final axis becomes the first axis. The middle axis stays in the middle. No axis is removed, and no new singleton axis is inserted.

For a concrete coordinate, x[1,2,3] equals 23. In the swapped view, the corresponding entry is swapped[3,2,1], also 23. The first and last coordinate components exchange places alongside their axes.

This operation does not rank, sort or aggregate the entries. It changes their axis-based interpretation.

NumPy swapaxes exchanges first and final axes

A row-shaped array can become column-shaped

For row = np.array([[2,5,8]]), the input shape is (1,3). The call np.swapaxes(row,0,1) produces shape (3,1) and displays [[2],[5],[8]].

This two-dimensional example exchanges the row and column axes. Its three values remain present, with the same correspondence between source entries and output coordinates.

A one-dimensional vector is different. An input with shape (3,) has only one axis, so there are not two distinct axes available to exchange. Add the intended structure explicitly before asking for an exchange that requires two axes.

Equal lengths can conceal the exchange

Consider cube = np.arange(8).reshape(2,2,2). Swapping axes zero and two leaves the shape (2,2,2), because the exchanged axes have the same length.

The coordinate correspondence still changes. The source entry cube[0,0,1] equals 1, while its corresponding entry after the exchange is at output coordinate [1,0,0].

An unchanged shape therefore does not prove an unchanged axis arrangement. Use axis names or a specific coordinate to explain the intended exchange when axis lengths are equal.

A view is not independent editable storage

For an ndarray input in current NumPy, swapaxes returns a view. Do not assume that changing the arrangement creates a separate copy of its values.

If later editing must remain independent of the source, use an explicit copy, such as independent = np.swapaxes(x,0,2).copy().

Applying the same exchange twice restores the original axis order. That reversibility concerns the arrangement of axes, not a promise that intermediate arrays own separate data.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the two exchanged axes, output shape and a corresponding coordinate before relying on the rearranged array.

NumPy moveaxis relocates selected axes while preserving the order of the others

An array's axes can describe different directions even when its numerical entries are unchanged. NumPy moveaxis relocates selected axes to chosen output positions. Academia Master Trader presents this English lesson for readers in Burkina Faso, using a constructed three-dimensional array to distinguish axis movement from reshaping, sorting and copying.

Moving the first axis to the end

After import numpy as np, define x = np.arange(24).reshape(2,3,4). Its shape is (2,3,4): axis zero has length two, axis one has length three and axis two has length four.

The call moved = np.moveaxis(x,0,-1) produces shape (3,4,2). The original first axis now occupies the last position. The other original axes keep their relative order: the length-three axis still precedes the length-four axis.

A concrete coordinate makes this change visible. The entry x[1,2,3] equals 23, and the corresponding entry in the moved view is moved[2,3,1], also 23.

The coordinate components follow the relocated axes. NumPy has not sorted the values or calculated new measurements.

NumPy moveaxis changes axis positions

Moving the last axis to the front

The call front = np.moveaxis(x,-1,0) produces shape (4,2,3). The original length-four axis becomes the first axis, while the length-two and length-three axes keep their relative order behind it.

For the same source entry, front[3,1,2] equals 23. Its coordinates differ from the previous result because a different axis movement was requested.

Negative positions count from the end. In a three-dimensional input, source position minus one refers to its final axis. Destination position zero means the first axis in the output.

Write down both the input axis labels and the intended output axis labels. The shape alone can be less informative when two axes happen to have equal lengths.

Several axes can move in one call

The call np.moveaxis(x,(0,2),(2,0)) produces shape (4,3,2). Original axis zero goes to output position two, and original axis two goes to output position zero. The remaining axis occupies the middle position.

Source positions must be unique, and destination positions must also be unique. Each selected source axis needs a corresponding destination position.

Think of the source and destination sequences as paired instructions, not as a request to perform unrelated movements one after another on an already changed shape.

Axis relocation returns a view

NumPy documents the result as a view of the input array. A different axis order therefore does not imply independent editable storage.

If later editing must not affect the source, make an explicit copy after the movement, such as independent = np.moveaxis(x,0,-1).copy().

Moving axes is also different from a general reshape. It carries the existing axes and their coordinate meanings to new positions rather than merely requesting another compatible shape.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the source axes, destination positions and one corresponding coordinate before relying on an axis relocation.

NumPy at least 3d inserts singleton axes according to the input dimensionality

A minimum of three dimensions does not identify one universal output shape. NumPy at least 3d follows different insertion rules for scalars, vectors and matrices. Academia Master Trader presents this English lesson for readers in Togo, using constructed inputs to explain those rules without confusing new axes with new numerical data.

A vector gains axes before and after its entries

After import numpy as np, define x = np.array([4,7,10]). Its shape is (3,). The call np.atleast_3d(x) returns an array with shape (1,3,1).

The original length-three axis becomes the middle axis. A singleton axis appears before it and another singleton axis appears after it. The result still contains three numerical entries.

This convention is more specific than simply adding dimensions somewhere. Shapes (1,1,3) and (3,1,1) also have three axes, but they are not the shape produced for this vector by this helper.

When a later expression assigns meaning to axis positions, write down the resulting shape before combining the data with other arrays.

NumPy at least 3d shape rules

A matrix gains one final singleton axis

For matrix = np.array([[1,2,3],[4,5,6]]), the input shape is (2,3). The call np.atleast_3d(matrix) produces shape (2,3,1).

The two existing axes keep their order and lengths. One new length-one axis follows them. This is not a transposition and does not combine the two original axes.

The six original entries remain present. Adding a final singleton direction does not repeat those six entries across several layers.

For a scalar, np.atleast_3d(9) produces shape (1,1,1). Its single value occupies an array with three singleton axes.

Existing higher-dimensional shapes are preserved

An input that already has three dimensions keeps its shape. For already = np.zeros((2,3,4)), the call np.atleast_3d(already) still has shape (2,3,4).

The same minimum rule permits more than three dimensions. For an input with shape (2,3,4,5), the output retains all four axes rather than collapsing them to three.

The helper therefore establishes a lower bound on dimensionality, not a fixed layout suitable for every later operation. A downstream function may impose additional requirements on axis order or axis lengths.

Multiple inputs remain separate arrays

The call a,b = np.atleast_3d([4,7,10],[[1,2],[3,4]]) returns separate arrays with shapes (1,3,1) and (2,2,1). It does not join those inputs into one object or make their shapes identical.

Non-array inputs are converted to arrays. Copies are avoided where possible, so an output view can share data with an existing source array.

If later edits need independent storage, take an explicit copy after applying the dimensionality rule. Shape conversion and ownership of editable values are separate decisions.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input dimensionality, inserted singleton axes and final shape before relying on the result.