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 cumprod records successive products along an array in its supplied order

Multiplication can be recorded as a sequence of intermediate results rather than only as a final product. NumPy cumprod returns those successive products along a chosen axis. Academia Master Trader presents this English lesson for readers in Mongolia. Constructed numerical examples explain the accumulation rule, the effect of zero, and the difference between flattening a matrix and working along one of its axes.

Multiply through the current position

After import numpy as np, define a = np.array([2,3,4,2]). The call np.cumprod(a) returns [2,6,24,48]. The first output is two. The next output is two times three. The third includes four as well, producing twenty four, and the last includes the final two to produce forty eight.

There are four output entries, matching the number of input entries. Cumprod does not insert a separate initial one before the sequence. It does not add the values or multiply each entry by its numeric position. Each output includes every input from the beginning of this accumulation through the corresponding current position.

NumPy cumprod

Intermediate products depend on order

Define b = np.array([4,2,2,3]). The call np.cumprod(b) returns [4,8,16,48]. These exact integer examples use the same factors and reach the same final product, but their intermediate results differ. The running sequence therefore describes the supplied arrangement, not only the collection of factors.

Keep that order explicit when factors represent successive stages in a calculation. A cumulative product does not decide whether an arrangement follows time, category or another coordinate. Nor does it establish that multiplying the supplied quantities is appropriate. Record what each factor means before assigning an interpretation to the returned numbers.

Zero carries through later finite products

For z = np.array([2,0,5,3]), the call np.cumprod(z) returns [2,0,0,0]. Once zero has entered this ordinary finite integer example, each later multiplication remains zero. Five and three are still present in the input, but the cumulative result no longer reveals their individual values.

A negative factor can change the sign of a nonzero running product. For example, np.cumprod([2,-3,4]) returns [2,-6,-24]. The result is a sequence of signed products, not absolute magnitudes. Keep the original factors if later work needs to distinguish the individual contributions that produced a total.

The default combines a flattened matrix

Define m = np.array([[2,3,2],[4,2,3]]). The default call np.cumprod(m) returns [2,6,12,48,96,288]. With no axis supplied, the input is flattened before accumulation. The result is a vector with six entries instead of a matrix shaped (2,3).

The first factor of the second row multiplies the product already reached at the end of the first row. Thus the fourth output is forty eight, not four. That default behavior is useful only when one continuous sequence across the flattened layout matches the intended calculation.

Choose an axis and accumulator type

The call np.cumprod(m,axis=1) returns [[2,6,12],[4,8,24]]. Each row accumulates independently. The call np.cumprod(m,axis=0) returns [[2,3,2],[8,6,6]], accumulating down each column instead. Both explicit axis results preserve the matrix shape, but they describe different groups of factors.

The dtype argument controls the output and accumulator type. Fixed width integer multiplication can overflow without raising an error, so choose a suitable type for the expected products. Changing the type does not decide the data meaning or guarantee exact arithmetic for every quantity. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the factor order, axis and numeric type with every cumulative product.

NumPy cumsum records running totals in the order an array is supplied

A final total compresses a whole sequence into one number. A cumulative sum records the total reached at each position along that sequence. Academia Master Trader presents this English lesson for readers in Turkmenistan. NumPy cumsum provides the running totals, while the analyst remains responsible for choosing a meaningful order, axis and numeric type. Constructed examples show what each returned entry includes.

Each output includes the current entry

After import numpy as np, define a = np.array([3,2,-1,5]). The call np.cumsum(a) returns [3,5,4,9]. The first output is three. The second is three plus two. The third includes the next entry, minus one, so the running total becomes four. The last output includes all four entries and equals nine.

The output has four entries rather than one. It does not automatically begin with a separate zero, and it is not an average. A negative input can make the cumulative sum decrease. The operation follows the sequence as supplied; it does not reorder values or infer which observation should come first.

NumPy cumsum

The path depends on the input order

Reorder the same numbers as b = np.array([5,-1,2,3]). The call np.cumsum(b) returns [5,4,6,9]. The last value is again nine in these exact integer examples, but the intermediate totals differ. A running total therefore carries information about the chosen arrangement, not merely about the collection of values.

If entries represent observations over time, keep the time coordinates and confirm their order separately. Cumsum does not inspect labels or decide whether the sequence is chronological. If entries belong to several unrelated groups, decide where accumulation should restart rather than treating a flattened collection as one continuous sequence without explanation.

The default flattens a matrix

Define m = np.array([[2,4,1],[3,5,2]]). The default call np.cumsum(m) returns [2,6,7,10,15,17]. With no axis specified, NumPy accumulates over the flattened array. The result is a one dimensional vector of six totals, even though the input has shape (2,3).

Here the first row contributes two, four and one before the second row contributes three, five and two. The first total associated with the second row is ten, not three, because the default accumulation continues from the first row. Keep that boundary visible when interpreting a flattened result.

An explicit axis preserves the matrix shape

The call np.cumsum(m,axis=1) returns [[2,6,7],[3,8,10]]. It accumulates across each row independently. The second row begins at three because its running total does not include entries from the first row. Both input and output have shape (2,3).

The call np.cumsum(m,axis=0) instead returns [[2,4,1],[5,9,3]]. It accumulates down each column. At the second row, five comes from two plus three, nine from four plus five, and three from one plus two. Name the data meaning of each axis before choosing the direction of accumulation.

Choose a suitable numeric type

The dtype argument controls the output and accumulator type. For example, np.cumsum(a,dtype=np.float64) returns floating point totals [3.,5.,4.,9.]. This changes their numeric representation, not the interpretation of the underlying entries.

Fixed width integer arithmetic can overflow without raising an error, so choose a type suitable for the expected totals. Floating point accumulation can also round, and its last entry may differ from a separate sum calculation. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the order, axis and accumulator type with the running totals.

NumPy diff calculates differences between adjacent entries along a chosen axis

A sequence of values and the differences between those values answer different questions. NumPy diff calculates the change from each entry to the next along a selected axis. Academia Master Trader explains the operation in English for readers in Kyrgyzstan. Constructed examples connect the subtraction rule, output length and axis choice without treating a difference as a percentage, a forecast or an independent measurement.

Subtract the earlier entry from the next

After import numpy as np, define a = np.array([3,7,6,12]). The call np.diff(a) returns [4,-1,6]. Seven minus three gives four. Six minus seven gives minus one. Twelve minus six gives six. The subtraction follows the supplied array order, not a separate chronological interpretation.

Four source entries produce three adjacent differences. Each output entry belongs to a pair of neighboring input positions. A positive result means that the later position has a larger value; a negative result means it has a smaller value. This describes the pair, not the reason for its change.

NumPy diff

A difference is not automatically a rate

The first result, four, is an absolute difference in the units of the input. It is not four percent. Computing a relative change would require a separately chosen denominator and a rule for cases where that denominator is zero. Likewise, a rate per hour requires information about the time between observations.

Diff does not inspect dates or infer equal time spacing from the order of an ordinary numeric vector. Keep any time coordinates with the source and state their meaning. If the array has been sorted by value rather than observation time, the neighboring pairs describe that sorted arrangement instead.

Higher order means differences of differences

The call np.diff(a,n=2) returns [-5,7]. It first forms [4,-1,6], then calculates minus one minus four and six minus minus one. These are second differences. They are not the changes between every second original entry, and they are not the first differences multiplied by two.

In this four entry example, one difference reduces the length to three and a second reduces it to two. The parameter n states how many times the differencing operation is applied. With n=0, the input is returned as it is. Keep the order visible when documenting a derived array.

The axis chooses the neighboring positions

Define m = np.array([[2,5,9],[4,10,15]]). The default call np.diff(m) returns [[3,4],[6,5]], because the default axis is the last one. Here that means moving across each row. The input shape (2,3) becomes (2,2).

By contrast, np.diff(m,axis=0) returns [[2,5,6]]. It subtracts the first row from the second at each column, producing shape (1,3). Neither result is more correct without knowing what rows and columns represent. Name the axis by its data meaning as well as its numeric label.

Boundary values and data types matter

The call np.diff(a,prepend=0) returns [3,4,-1,6]. Zero is added before the first input entry for the calculation, so the new first difference is three minus zero. The output has four entries, but its first pair includes an explicitly supplied boundary value rather than two original observations.

Unsigned integer arrays also need attention. An unsigned eight bit array containing [1,0] produces [255] under diff, rather than a signed minus one. Convert to a suitable signed type before subtraction when negative results are intended. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the order, axis, difference order and any boundary value alongside the result.

NumPy clip limits array values at chosen edges without removing positions

An array can keep its layout while selected values are limited to a chosen interval. NumPy clip replaces values below a lower edge with that edge and values above an upper edge with the upper edge. Academia Master Trader presents this English lesson for readers in Tajikistan. Constructed examples explain how clipping differs from filtering, rescaling and changing the source array in place.

Keep the values already inside the interval

After import numpy as np, define a = np.array([-3,1,4,9,12]). The call np.clip(a,0,10) returns [0,1,4,9,10]. Minus three becomes zero because it is below the lower edge. Twelve becomes ten because it is above the upper edge. One, four and nine stay unchanged.

The result has five entries, just like the input. Clipping does not remove the values outside the interval or shorten the array. Nor does it stretch all values onto a new scale. It only applies the specified limits. A value equal to an edge remains equal to that edge.

NumPy clip

A limited value does not identify its original

In the output, zero could have come from an original zero or from any value below zero. Ten could have come from an original ten or from a larger value. Once those distinctions are replaced by the edges, the clipped output alone cannot reconstruct the original entries.

Keep the source when those distinctions matter. In the call above, a is unchanged because no output destination was specified. Store the result under a separate name, such as limited = np.clip(a,0,10), when both the original and the limited representation are useful. The new name describes the transformation without suggesting that the original measurements were incorrect.

Use None for an unlimited edge

A bound can be None when clipping should not apply on that side. For the same a, np.clip(a,None,8) returns [-3,1,4,8,8]. The upper edge becomes eight, while negative values stay untouched because there is no lower limit in this call.

Conversely, np.clip(a,2,None) returns [2,2,4,9,12]. Only the lower edge applies. Twelve remains twelve. This is different from supplying zero as a bound: zero is an actual numeric limit, while None means that the corresponding edge does not perform clipping.

Array bounds can vary by position

The bounds can be arrays that broadcast against the input. Define lower = np.array([0,2,3,4,5]). The call np.clip(a,lower,10) returns [0,2,4,9,10]. Each input entry uses the lower edge at the corresponding position, while the scalar upper edge ten applies throughout.

The lower array is not a second set of observations to concatenate with a. It supplies limits. Check the shapes and the meaning of every bound before applying a position dependent rule. Broadcasting must produce compatible positions for the values and bounds; unrelated lengths do not automatically define a valid arrangement.

Check edge order before clipping

NumPy does not check that the lower edge is less than the upper edge. With reversed scalar edges, np.clip(a,10,0) returns [0,0,0,0,0]. The documented behavior makes every entry equal to the upper edge in this case. Do not expect the function to swap the two numbers or report an interval ordering error.

The optional output argument also changes how the result is stored. The call np.clip(a,0,10,out=a) writes the clipped values into a itself. This deliberately replaces the original entries, unlike the earlier calls. Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. State the bounds, confirm their order and choose the output destination explicitly.

NumPy where chooses between two alternatives at each position of an array

A condition can decide which of two alternatives supplies each output entry. In its three argument form, NumPy where selects from the first alternative when the condition is true and from the second when it is false. Academia Master Trader explains that form in English for readers in Uzbekistan. Constructed examples show how the selection preserves a common output shape instead of simply dropping the positions where a condition is false.

Choose a value at every position

After import numpy as np, define a = np.array([2,5,8,11]). The expression np.where(a < 7,a,0) returns [2,5,0,0]. The condition is [True,True,False,False]. At the first two positions, the output comes from a. At the remaining positions, it comes from the scalar zero.

The result still has four entries. Where has not removed eight and eleven to produce a shorter vector. It has filled their corresponding output positions with the false alternative. The original a retains its values because this call constructs a result rather than assigning that result back into a.

NumPy where

Both alternatives can be arrays

Define b = np.array([20,50,80,110]). The call np.where(a < 7,a,b) returns [2,5,80,110]. At each true position it selects the value from a at that position. At each false position it selects the value from b at that position. It does not take all of a first and append part of b afterward.

Reversing the alternatives reverses their roles. The expression np.where(a < 7,b,a) returns [20,50,8,11]. The condition stays the same, but true now selects from b and false selects from a. State the roles of the second and third arguments when explaining a selection, particularly if both contain plausible output values.

Matrices retain their selection layout

Define m = np.array([[1,4],[7,10]]). The call np.where(m < 6,m,-1) returns [[1,4],[-1,-1]]. The condition and output have shape (2,2). Each output position corresponds to the same row and column position in the source matrix.

This makes where different from a filtering operation that gathers only matching entries into a vector. A matrix shaped result can retain the placement of both matched and unmatched positions. The replacement value minus one is part of the chosen rule. It does not establish that the original entries were negative, absent or incorrectly recorded.

Broadcasting defines the common shape

The condition and both alternatives must be broadcastable to a common shape. A scalar alternative can supply the same value across many positions, as zero and minus one do above. Equal shaped arrays also fit the rule. Inputs that cannot broadcast to a common shape raise an error instead of defining a meaningful position by position selection.

For example, np.where([[True],[False]],[10,20,30],-1) returns [[10,20,30],[-1,-1,-1]]. The two by one condition and the three entry alternative broadcast to shape (2,3). The first condition row selects the vector, while the second selects the scalar. Check this output shape before using a broadcast selection in another calculation.

Keep the one argument form separate

Calling where with only a condition has a different purpose: it returns the nonzero positions as a tuple of index arrays. It does not provide two alternatives or return the selected source values. The documentation recommends using nonzero directly for that purpose. Do not read a one argument call as shorthand for the three argument selection described here.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the condition, true alternative, false alternative and common shape. Then trace the output position by position so the selection rule remains explicit.

NumPy select applies ordered conditions and uses the first matching choice at each position

Several conditions can describe alternative ways to fill an output array. NumPy select pairs each condition with a choice and gives priority to the first matching condition at each position. Academia Master Trader explains this rule in English for readers in Kazakhstan. Constructed examples show how overlaps, defaults and list order determine the result. Writing the rules down makes the selection easier to follow than looking only at the final values.

Pair conditions with their choices

After import numpy as np, define x = np.array([1,3,5,7]). Set conditions = [x < 4,x > 6] and choices = [x * 10,x + 100]. The call np.select(conditions,choices,default=-1) returns [10,30,-1,107]. The first condition selects ten times x, and the second selects x plus one hundred.

At values one and three, the first condition is true, so their outputs are ten and thirty. At five, neither condition is true, so the output is the default minus one. At seven, the second condition is true, producing one hundred and seven. The condition list and choice list must contain the same number of entries.

NumPy select

The first true condition has priority

Now set conditions = [x < 6,x > 2], while retaining the same choices. The call np.select(conditions,choices,default=-1) returns [10,30,50,107]. At three and five, both conditions are true. The first condition supplies the output, so those positions use ten times x rather than x plus one hundred.

The function does not combine the matching choices or select the largest numerical result. It uses list order as the priority rule. This matters when two conditions overlap even if the example appears to describe separate categories. Inspect their Boolean arrays directly instead of assuming that every position can satisfy only one condition.

Reordering changes the priority rule

If the condition and choice pairs are reversed together, the overlap is handled differently. The expression np.select([x > 2,x < 6],[x + 100,x * 10],default=-1) returns [10,103,105,107]. At three and five, the condition naming x plus one hundred is now encountered first.

Keep each condition beside its matching choice when changing order. Reordering only one list changes the pairing as well as the priority and can express a different rule from the one intended. A short written mapping, such as less than six means ten times x, helps preserve the relationship between each condition and its output.

A default covers positions with no match

The default argument supplies an output wherever every condition is false. If it is omitted, the documented default is zero. For the initial conditions, np.select([x < 4,x > 6],[x * 10,x + 100]) returns [10,30,0,107]. The zero at the position containing five comes from that default.

An output value alone does not reveal whether it came from a choice or the default, particularly when a choice can produce the same value. Retain the conditions and rule description when that distinction matters. A default is part of the selection design, not evidence that the corresponding source value was zero or missing.

Read each output through the ordered rules

Select fills the output position by position using the supplied condition and choice pairs. In these examples, x retains its original values. The transformed numbers belong to the constructed output; they do not replace the source merely because the rule mentions x.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Check the pairings, inspect overlaps and state the default explicitly. Then trace each result back to the first true condition. This keeps a multi condition selection understandable without assigning hidden meaning to its priority order.

NumPy choose uses integer codes to select from corresponding positions in choice arrays

Selecting from several arrays requires a rule about which array supplies each output entry. NumPy choose uses integer codes to express that rule. Academia Master Trader explains the operation in English for readers in Azerbaijan. Constructed examples show how a code selects a source array while the output position determines which entry is taken from that source. This is different from simply retrieving positions within one vector.

Match each code to a choice array

After import numpy as np, define low = np.array([10,20,30]) and high = np.array([100,200,300]). The expression np.choose([0,1,0],[low,high]) returns [10,200,30]. Code zero names low, the first choice array. Code one names high, the second choice array.

At output position zero, code zero selects low's entry at position zero, which is ten. At position one, code one selects high's entry at position one, which is two hundred. At position two, code zero selects low's entry at position two, which is thirty. Both the code and the position matter.

NumPy choose

A code does not name an entry within one vector

The codes [0,1,0] do not mean to retrieve positions zero, one and zero from low. They identify which member of the choice sequence supplies the value at each output position. This distinction explains why the final entry is thirty rather than ten in the example above.

Keep the choices in an explicit list or tuple. The sequence order establishes the meaning of each integer code. Reversing the choices while leaving the code array unchanged changes the selection rule. For example, np.choose([0,1,0],[high,low]) returns [100,20,300]. Document the code mapping beside the data instead of assuming that zero always names a particular category.

Scalar choices can fill a shaped code array

The call np.choose([[0,1],[1,0]],[5,9]) returns [[5,9],[9,5]]. Each scalar choice is broadcast across the shape of the code array. Zero selects five and one selects nine at each of the four positions. The resulting array has shape (2,2).

The code array and every choice must be broadcastable to a common shape. Equal shapes satisfy that requirement, but they are not the only possibility, as the scalar example shows. Check the common shape when using more complicated inputs. An unexpected shape can change the arrangement of the output even when the code values look familiar.

Default mode requires valid choice codes

With two choices, the valid codes in the default mode are zero and one. A code of two is outside that range and raises an error. The upper limit depends on the number of choices, not on the number of entries within each choice array.

For the three entry low and high arrays, np.choose([0,2,1],[low,high],mode='wrap') returns [10,20,300]. Wrap maps code two back to zero because there are two choices. The same call with mode clip returns [10,200,300], since clipping maps code two to the highest valid code, one. Choose the boundary rule deliberately rather than treating these modes as interchangeable corrections.

Read the result through its source mapping

A selected value remains the entry from its chosen source at the corresponding position after broadcasting. Choose does not average the alternatives or combine their magnitudes. The output is an arrangement governed by the supplied codes, choice sequence and boundary mode.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the code mapping, common shape and mode. Trace a few output positions back to their source entries. This makes the selection understandable without assigning extra meaning to the numerical codes themselves.

NumPy extract gathers entries selected by a condition into a one dimensional array

A condition can select individual entries from a matrix without keeping its original row and column arrangement. NumPy extract returns those selected values as a one dimensional array. Academia Master Trader explains the operation in English for readers in Armenia. Constructed examples show how a condition maps to positions, how the output order is determined and why a selected vector is not a smaller rectangular version of the original matrix.

Apply a condition to a small matrix

After import numpy as np, define m = np.array([[2,5,8],[11,14,17]]). This matrix has two rows and three columns. The comparison condition = m > 9 produces [[False,False,False],[True,True,True]]. Each Boolean entry describes whether the value at that same position is greater than nine.

The call np.extract(condition,m) returns [11,14,17]. It gathers the three values marked true and places them in a vector. The result has shape (3,), not (1,3). Although the selected values came from one row in this particular example, extract does not retain that row dimension.

NumPy extract

Selection can cross row boundaries

Consider condition = m % 2 == 0. The remainder calculation identifies even values, giving [[True,False,True],[False,True,False]]. The expression np.extract(condition,m) returns [2,8,14]. These selected entries come from different rows and columns, yet the output is still one dimensional.

The function follows the flattened input sequence, which here is [2,5,8,11,14,17]. It keeps the entries whose corresponding condition positions are true. The order is therefore two, eight and fourteen. It does not group entries by column or sort them as a separate operation. Any numerical ordering in this example comes from the original arrangement.

Think of values and condition being flattened together

The documented operation is equivalent to applying compress to the flattened condition and the flattened source array. For the even value example, the condition sequence is [True,False,True,False,True,False]. Applying it to the flattened values retrieves exactly the same three entries.

Use an input and condition with the same number of entries, as the interface specifies. A Boolean condition with the same shape as the input is usually easiest to read because each position aligns visibly. Write the condition from the intended rule, then inspect it beside the source instead of assuming it selects the entries you had in mind.

Numerical conditions select nonzero positions

The condition can also contain numerical entries. Nonzero entries indicate positions to retain, while zero entries indicate positions to omit. For example, np.extract([0,2,0,-1],[10,20,30,40]) returns [20,40]. The two and minus one act as selection signals; they do not multiply the retrieved values.

A Boolean condition is often clearer when explaining a filtering rule, because true and false state the choice directly. If numerical conditions are used, explain their nonzero interpretation so that readers do not mistake their magnitudes for weights. A retained entry remains the original value from its source position.

Keep the selection distinct from the source

The source matrix still contains all six original entries after extraction. The returned vector describes the subset selected by the stated condition. Its shorter length does not establish that omitted entries were invalid, unavailable or absent from the source. Those interpretations would require information beyond the selection itself.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape and the rule used to build the condition. Check which positions are true and confirm the one dimensional output. This keeps array filtering clear without turning a selection rule into an unsupported conclusion about the underlying data.

NumPy compress selects array slices where a one dimensional condition is true

A Boolean condition can describe which positions to keep from an array. NumPy compress uses a one dimensional condition to select slices along a chosen axis. Academia Master Trader explains this operation in English for readers in Georgia. Constructed vectors and matrices show the relationship between condition positions, retained entries and output shape. Selecting a subset changes which entries are present, not the meaning of the original observations.

Keep the entries marked true

After import numpy as np, define x = np.array([12,24,36,48]). The call np.compress([True,False,True,False],x) returns [12,36]. Positions zero and two are kept because the corresponding condition entries are true. Positions one and three are omitted because their condition entries are false.

The condition follows positions in the input. It does not name the numerical values to retrieve, and it does not arrange the retained entries by size. The selected entries appear in their original sequence. Reading the condition beside the input is a simple way to check which positions contribute to the result.

NumPy compress

Select complete rows with axis zero

Define m = np.array([[1,2],[3,4],[5,6]]), with shape (3,2). The expression np.compress([True,False,True],m,axis=0) returns [[1,2],[5,6]]. Each true condition entry retains a complete row. The middle row is omitted, and the result has shape (2,2).

The condition has three positions because the selected row dimension has length three. Two true entries produce two retained rows. The other dimension still has length two, because the selection retains both columns within every selected row. Counting true entries helps predict the output length along the selected axis.

Select columns with axis one

The call np.compress([False,True],m,axis=1) returns [[2],[4],[6]]. This condition addresses the two column positions. Only the second column is retained, so the output has shape (3,1). All three rows remain in the result.

A two dimensional result with one column is different from a one dimensional vector. The brackets show that each retained entry still belongs to a row containing one column. State the output shape when explaining this selection so that a later calculation does not silently assume a different number of dimensions.

A missing axis means a flattened selection

With no axis argument, compress works on the flattened input. For the matrix m, the call np.compress([False,True],m) returns [2]. The flattened sequence begins with one and two. The two entry condition addresses those first two positions, keeping only the second.

This example also illustrates a documented detail: when the condition is shorter than the selected dimension, only the positions covered by the condition participate. The remaining positions are not selected automatically. Prefer a condition that matches the intended axis length when you want to make a decision about every position, and check the lengths explicitly.

The output is a copy

Compress returns a copy rather than a view of the selected slices. For example, create selected = np.compress([True,False,True,False],x). Setting selected[0] = 99 changes the first entry of selected, while the original x still begins with twelve. This behavior differs from operations that return views sharing the source storage.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the condition, its length and the selected axis before filtering. Inspect the output shape and retained positions afterward. This keeps selection rules visible without treating an omitted entry as if it never existed in the source array.

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

A list of positions can describe a deliberate selection from an array. NumPy take retrieves entries in that requested order, including repeated positions when they appear in the index list. Academia Master Trader explains the operation in English for readers in Ukraine. Small constructed vectors and matrices show how axis selection changes the meaning of a position and how an index array can shape the output.

Select positions rather than numerical values

After import numpy as np, define x = np.array([10,20,30,40]). The call np.take(x,[3,0,3]) returns [40,10,40]. Position three supplies forty, position zero supplies ten and the repeated position three supplies forty again. The function follows the index sequence rather than sorting the selected values.

Python uses zero based indexing here: the first entry is at position zero. The list [3,0,3] names positions, not the values three and zero. Repetition in the result comes from repetition in the selection. It does not mean that the original vector has gained another independently recorded entry.

NumPy take

Select columns with an explicit axis

Define m = np.array([[1,2,3],[4,5,6]]), which has shape (2,3). The expression np.take(m,[2,0],axis=1) returns [[3,1],[6,4]]. It selects column position two and then column position zero while keeping both rows. The result has shape (2,2).

With np.take(m,[1,0],axis=0), the result is [[4,5,6],[1,2,3]]. This selection requests row position one before row position zero. The numerical index one has a different role depending on the selected axis. Write both the axis and the intended positions when explaining a matrix selection.

Omitting the axis uses a flattened input

The call np.take(m,[2,0]) returns [3,1]. With the default axis value of None, take treats the input as flattened instead of selecting complete columns. In this example, the flattened sequence is [1,2,3,4,5,6]. Positions two and zero therefore retrieve three and one.

Compare that one dimensional result with the two dimensional column selection made using axis one. The same index list can produce different shapes and groupings because the axis setting defines the selection context. Include that setting in a reusable example rather than relying on a reader to infer it from the returned numbers.

The index array can have its own shape

For the original vector x, np.take(x,[[0,2],[3,1]]) returns [[10,30],[40,20]]. The two by two arrangement of indices produces a two by two arrangement of selected entries. Each index supplies one value from the vector at the corresponding output position.

For a general axis selection, the index array's dimensions replace the selected axis in the output shape. Dimensions before and after that axis remain around them. For example, applying that two by two index array to the columns of a two row matrix would add both index dimensions between the retained row dimension and any dimensions that follow the selected axis.

Decide how outside positions should behave

The default mode raises an error for an index outside the valid range. The mode named wrap maps indices around the axis length. The mode named clip restricts them to the range endpoints. For x, np.take(x,[4],mode='wrap') returns [10], while np.take(x,[4],mode='clip') returns [40].

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the input shape, selected axis, index sequence and boundary mode. Check output shape as well as values. These details explain the selection without confusing repeated retrieval with additional source data.